You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Ansible清单文件中移除或注释主机SVC1?

问题描述

我的/etc/ansible/inventory文件内容如下:

[applications]
SVC1 ansible_host=10.252.20.208
SVC2 ansible_host=10.252.20.209

我需要用Ansible模块移除或注释清单里的SVC1主机条目,预期修改后的文件内容如下:

[applications]
# SVC1 ansible_host=10.252.20.208
SVC2 ansible_host=10.252.20.209

场景说明:SVC1上运行着一个应用,我希望在执行Ansible卸载脚本时,自动完成清单条目的注释/移除操作。

我试过以下配置,但没成功:

---
- name: update inventory
  hosts: all
  run_once: true
  tasks:
    - name: Remove the peer configuration for 10.128.0.11/32
      community.general.ini_file:
        path: /etc/ansible/inventory
        section: applications 
        option: SVC1
        state: absent
      delegate_to: localhost
      run_once: true
解决方案

方案1:用lineinfile注释目标条目

ini_file模块更适合处理标准key=value格式的配置项,而你的清单条目是主机别名加参数的结构,改用lineinfile模块更合适。通过精确匹配目标行,在开头添加注释符号:

- name: 注释inventory中的SVC1条目
  hosts: localhost
  tasks:
    - name: 注释SVC1主机条目
      ansible.builtin.lineinfile:
        path: /etc/ansible/inventory
        regexp: '^SVC1 ansible_host=10.252.20.208$'
        line: '# SVC1 ansible_host=10.252.20.208'
        backrefs: true
  • 注意:backrefs参数确保只有匹配到精确行才执行替换,避免误修改其他内容。

方案2:用lineinfile直接移除条目

如果不需要保留注释,直接删除目标行的话,设置state: absent即可:

- name: 移除inventory中的SVC1条目
  hosts: localhost
  tasks:
    - name: 删除SVC1主机条目
      ansible.builtin.lineinfile:
        path: /etc/ansible/inventory
        regexp: '^SVC1 ansible_host=10.252.20.208$'
        state: absent

原配置失败原因

community.general.ini_file的option参数对应ini文件里的键(即key=value中的key),但你的清单条目不是标准键值对格式,模块无法识别SVC1为有效option,所以操作无效。

内容的提问来源于stack exchange,提问作者Arjun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 17:45:10