/etc/hosts
如果有新数据,我想插入行或更新我的行。我的以下剧本正在使用lineinfile
,但是,我遇到了一个问题,当我的一台服务器获得新IP时,该模块基本上会添加包含新IP的新行,这很好,但旧的仍然存在。
我想尽可能简洁,希望只使用 1 个模块,而不是lineinfile
&的组合replace
。
现有剧本示例
- ansible.builtin.lineinfile:
path: /etc/hosts
line: "{{ hostvars[item].ansible_all_ipv4_addresses.0 }} {{ hostvars[item].ansible_hostname }} {{ hostvars[item].ansible_hostname }}"
loop: "{{ groups['web'] }}"
所以......我基本上最终得到:
/etc/主机
192.168.1.1 web1.example.com web1
192.168.1.2 web2.example.com web2
192.168.1.3 web3.example.com web3
配置新的 web2:
192.168.1.1 web1.example.com web1
192.168.1.2 web2.example.com web2
192.168.1.3 web3.example.com web3
192.168.1.4 web2.example.com web2
您需要使用该
regexp
选项来告知lineinfile
要替换哪些行。这可能看起来像这样:在我的测试环境中,第一次运行它会产生:
如果我更新 的 IP 地址
web2
,我会得到:Ansible 已替换了 的行
web2.example.com
,而不是附加新行。从 2.11 开始,您可以使用更简单的search_string而不是regexp。例如,给定用于测试的库存
下面的玩法是幂等的
在控制器上创建文件/tmp/hosts