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.
This code will replace
DNS<N>
with corresponding value fromsrv_list
if it is present in the file, or add new line if DNS with such index is not defined in the file.