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

如何实现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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 13:50:20