如何实现ansible.builtin.lineinfile任务幂等性,避免重复添加内容?
解决Ansible lineinfile任务重复添加内容的幂等性问题
你的问题根源在于原任务的正则会匹配所有以hosts:开头的行,不管该行是否已经包含libvirt_guest,导致每次运行都会在末尾重复追加内容。要实现幂等性,只需调整正则表达式,让它只匹配**尚未包含libvirt_guest**的hosts:行即可。
修改后的任务代码
- name: Enable libvirt_guest dns via nss ansible.builtin.lineinfile: path: /etc/nsswitch.conf regex: ^(hosts:.*)(?!.*libvirt_guest) line: \1 libvirt_guest backrefs: true become: true
关键修改说明
- 正则表达式
^(hosts:.*)(?!.*libvirt_guest)使用负向预查(?!...),确保匹配到的hosts:行中不存在libvirt_guest字符串。 - 只有当目标行确实缺少
libvirt_guest时,任务才会执行替换操作;如果该行已包含该内容,正则将无法匹配,任务会直接跳过修改,从而实现幂等性。
另一种直观写法
如果觉得捕获组处理麻烦,也可以直接引用原始匹配行:
- name: Enable libvirt_guest dns via nss ansible.builtin.lineinfile: path: /etc/nsswitch.conf regex: ^hosts: (?!.*libvirt_guest).* line: '{{ ansible_original_line }} libvirt_guest' backrefs: false become: true
内容的提问来源于stack exchange,提问作者sbates-nvme
相关产品推荐
相关产品推荐

