如何让Ansible确保dhcpcd.conf中仅保留一行指定静态IPv6地址?
问题描述
原Ansible剧本试图配置静态IPv6地址,但执行后没有替换已有的多行匹配配置,反而新增了一行,无法达到仅保留目标IPv6地址的效果。
原剧本任务:
- name: Configure stable IPv6 lineinfile: path: /etc/dhcpcd.conf regexp: '^static ipv6_address=' line: "static ip6_address=2001::2222/64" state: present notify: Restart dhcpcd
服务器初始/etc/dhcpcd.conf内容:
# fallback to static profile on eth0 #interface eth0 #fallback static_eth0 static ip6_address=2001::0000/64 static ip6_address=2001::1111/64
执行后不符合预期的结果:
# fallback to static profile on eth0 #interface eth0 #fallback static_eth0 static ip6_address=2001::0000/64 static ip6_address=2001::1111/64 static ip6_address=2001::2222/64
期望的最终配置:
# fallback to static profile on eth0 #interface eth0 #fallback static_eth0 static ip6_address=2001::2222/64
核心需求:
- 配置中无匹配行时,添加目标IPv6配置行
- 存在匹配行时,移除所有匹配行,只保留目标单行配置
解决方案
推荐用两个任务组合实现需求,逻辑清晰且能覆盖所有场景:
# 第一步:删除所有已存在的static ipv6_address配置行 - name: Remove all existing static IPv6 entries lineinfile: path: /etc/dhcpcd.conf regexp: '^static ipv6_address=' state: absent # 第二步:添加目标静态IPv6地址配置 - name: Add target static IPv6 address lineinfile: path: /etc/dhcpcd.conf line: "static ip6_address=2001::2222/64" state: present notify: Restart dhcpcd
补充方案(单任务实现)
如果想用单个任务完成,可以使用replace模块,通过正则匹配所有连续的目标行并替换:
- name: Configure stable IPv6 with replace replace: path: /etc/dhcpcd.conf # 匹配所有连续的static ipv6_address开头的行 regexp: '(^static ipv6_address=.*\n)+' replace: "static ip6_address=2001::2222/64\n" # 可选:开启备份防止配置出错 backup: yes notify: Restart dhcpcd
注意:如果原本没有任何匹配行,这个任务不会添加目标行,因此需要额外加一个任务确保目标行存在,所以第一个两行任务的方案更稳妥。
内容的提问来源于stack exchange,提问作者izidor
相关产品推荐
相关产品推荐

