给定要测试的文件
shell> cat /tmp/ansible/test/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
将配置数据放入列表
dhcpcd_conf:
- {key: static ip6_address, value: 2001::2222/64}
删除重复的参数,但删除第一个参数
- name: "Remove duplicate parameters from dhcpcd.conf"
ansible.builtin.replace:
dest: /tmp/ansible/test/dhcpcd.conf
after: '{{ item.key }}(\s|=)'
regexp: '^\s*{{ item.key }}(\s|=).*$'
loop: "{{ dhcpcd_conf }}"
gives(使用选项--check--diff运行)
--- before: /tmp/ansible/test/dhcpcd.conf
+++ after: /tmp/ansible/test/dhcpcd.conf
@@ -2,4 +2,4 @@
#interface eth0
#fallback static_eth0
static ip6_address=2001::0000/64
-static ip6_address=2001::1111/64
如果你想保留最后一场比赛
之后
具有
之前
- name: "Remove duplicate parameters from dhcpcd.conf"
ansible.builtin.replace:
dest: /tmp/ansible/test/dhcpcd.conf
before: '{{ item.key }}(\s|=)'
regexp: '^\s*{{ item.key }}(\s|=).*$'
loop: "{{ dhcpcd_conf }}"
配置文件
- name: "Configure dhcpcd.conf"
ansible.builtin.lineinfile:
dest: /tmp/ansible/test/dhcpcd.conf
regexp: '^\s*{{ item.key }}(\s|=).*$'
line: "{{ item.key }}={{ item.value }}"
loop: "{{ dhcpcd_conf }}"
gives(使用选项--check--diff运行)
--- before: /tmp/ansible/test/dhcpcd.conf (content)
+++ after: /tmp/ansible/test/dhcpcd.conf (content)
@@ -1,5 +1,5 @@
# fallback to static profile on eth0
#interface eth0
#fallback static_eth0
-static ip6_address=2001::0000/64
+static ip6_address=2001::2222/64
完整的测试剧本示例
- hosts: localhost
vars:
dhcpcd_conf:
- {key: static ip6_address, value: 2001::2222/64}
tasks:
- name: "Remove duplicate parameters from dhcpcd.conf"
ansible.builtin.replace:
dest: /tmp/ansible/test/dhcpcd.conf
after: '{{ item.key }}(\s|=)'
regexp: '^\s*{{ item.key }}(\s|=).*$'
loop: "{{ dhcpcd_conf }}"
tags: duplicates
- name: "Configure dhcpcd.conf"
ansible.builtin.lineinfile:
dest: /tmp/ansible/test/dhcpcd.conf
regexp: '^\s*{{ item.key }}(\s|=).*$'
line: "{{ item.key }}={{ item.value }}"
loop: "{{ dhcpcd_conf }}"
tags: configure
结果
shell> cat /tmp/ansible/test/dhcpcd.conf
# fallback to static profile on eth0
#interface eth0
#fallback static_eth0
static ip6_address=2001::2222/64