用三条线代替两条线

我正在更换我们的DNS服务器。 作为其中的一部分,我们静态configuration的服务器接口的DNS条目需要更新。 但是,我遇到了一个障碍。 接口目前有2个条目定义,我想用3replace它们。

这个剧本演示了使用replace的问题。 它将取代DNS1和DNS2,但不能添加DNS3。 lineinfile有类似的问题。

 --- - hosts: canary vars: nameservers: [ '', 192.0.2.1, 192.0.2.2, 192.0.2.3 ] tasks: - name: nameservers replace: path: /etc/sysconfig/network-scripts/ifcfg-{{ansible_default_ipv4.interface}} replace: \1="{{ item.1 }}" regexp: (DNS{{ item.0 }}).+ with_indexed_items: - "{{ nameservers }}" when: ansible_distribution == "CentOS" and "nameservers" not in group_names tags: - debug 

lineinfile什么问题?
如果线正则expression式在那里,线将被replace; 否则将添加新行。

 --- - hosts: localhost gather_facts: no vars: srv_list: [192.168.0.1, 192.168.0.2, 192.168.0.3] tasks: - lineinfile: dest: /tmp/dns_test regexp: ^DNS{{ item.0+1 }} line: DNS{{ item.0+1 }}={{ item.1 }} with_indexed_items: "{{ srv_list }}" 

如果该文件中存在该代码,则该代码将用srv_list相应值replaceDNS<N> ,或者如果该文件中没有定义具有该索引的DNS,则添加新行。