I have been working on this for days. I don’t mind because I am learning a ton of stuff (as I am new to ansible), but the only way I can get this to work properly is to use a shell: module (utilizing sed). I would prefer to avoid that if I can.
Tasks:
Gather list of ifcfg-* files (except ifcfg-lo)
Add DNS entries if missing; otherwise replace DNS entries if they don’t match or
`
- name: Gather list of ifcfg-* files
shell: ls “{{ net_path }}” | grep ^ifcfg- | grep -ve ifcfg-lo -e @ # @ excludes ansible backup files
register: ifcfg_list
changed_when: false
`
The above works fine… it is the second task that is getting me.
Using the above I have tried all sorts of things. I have learned that lineinfile regexp only matches the last found match, replace matches all. blockinfile also appears to only to affect the last found match.
Anyway, how would you approach this without shell:?
As an example:
I wish to use the following vars as my dns entries:
dns1=10.10.10.10
dns2=20.20.20.20
ifcfg-eth0 contains:
DNS1=1.2.3.4
DNS2=2.3.4.5
ifcfg-eth1 doesn’t contain any dns entries
Hmmm… I am trying it this way… and am really close. I just don’t know how to properly reference variables in a regexp statement within ansible:
`
- name: TEST
replace:
path: “{{ net_path }}{{ item }}”
regexp: “^DNS(?!.(?:10.10.10.1[12])).”
with_items: “{{ ifcfg_list.stdout_lines }}”
`
I want to replace 10.10.10.1[12] with the variables dns1 and dns2
Got it… but if someone has a better way of doing this, I am all ears. I will add dns through the lineinfile module
`
Enter code here…- name: TEST
replace:
path: “{{ net_path }}{{ item }}”
regexp: “^DNS(?!.(?:{{ dns1 }}|{{ dns2 }})).”
with_items: “{{ ifcfg_list.stdout_lines }}”
`
I have a template for ifcfg-* files where I not only fill in DNS entries but also all the other network configuration
stuff. I put this into a role and all variables are in host_vars/*.yaml files. Every time I wish to change the
configuration I change the host_vars file and reapply the role (which creates a new ifcfg file from the template with
the new settings).
Yes that sounds very close to what I am trying to do. I can see how doing that with a template and a host_vars file would simplify it. Thank you for your input