Replace two line with three lines using ansible

ansible

I am changing out our DNS servers. As part of this the DNS entries for our statically configured server interfaces need to be updated. However, I'm running into a snag. The interfaces currently have 2 entries defined and I would like to replace them with 3.

This playbook demonstrates the problem using replace. It will replace DNS1 and DNS2, but cannot add DNS3. lineinfile has similar issues.

---
- 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

Best Answer

What is the problem with lineinfile?
If line regexp is there, line will be replaced; otherwise new line will be added.

---
- 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 }}"

This code will replace DNS<N> with corresponding value from srv_list if it is present in the file, or add new line if DNS with such index is not defined in the file.