I'm trying to edit the 01-netcfg.yml file with Ansible. Below is the file:
network:
version: 2
renderer: NetworkManager
ethernets:
enp0s31f6:
dhcp4: no
nameservers:
addresses: [8.8.8.8, 8.8.4.4]
enp12s0:
dhcp4: no
addresses:
- 192.168.0.1/24
enp8s0:
dhcp4: no
addresses:
- 192.168.1.1/24
enp9s0:
dhcp4: no
addresses:
- 192.168.16.1/24
I'm trying to change the dhcp4 value from no to yes under enp0s31f6 only.
- lineinfile:
path: /etc/netplan/01-netcfg.yaml
regexp: ' dhcp4: no'
line: ' dhcp4: yes'
insertbefore: ' nameservers:'
firstmatch: True
state: present
When I run the above code, it is modifying the dhcp4 under enp0s31f6 and also the dhcp4 under enp12s0. I tried insertafter as well, but same result.
Q: "Change the dhcp4 value from no to yes under enp0s31f6 only."
Given the file for testing
A: Do not use the module lineinfile (1) in this use_case. The module replace (2) might be a better option. The best option is to fetch, update, and copy the file (3).
Generally, the module lineinfile is not able to update any neplane interface's parameter. In the particular case of the given file, the task below does the job
Running the play with the options --check --diff gives
This works because the interface
enp0s31f6is first in theethernetskeys.Notes:
backrefs: true. Put the leading whitespace into the group\1firstmatch: true. The default false would match the lastdhcp4in the interfaceenp9s0. Quoting from regexp: "Only the last line found will be replaced."This doesn't work if the interface
enp0s31f6is not the first in the dictionaryethernets. For example,The task below, even with the option
insertafter: enp0s31f6gives
because
insertafterdoesn't work ifregexpis matched. Quoting from regexp:If you remove the option
regexpthe optionbackrefscan't work, and the regexp group\1can't be used inline. Then, the task belowdoesn't replace the existing parameter
dhcp4: no. Instead, a new one will be addedThe module replace seems to be a better option. The task below
does the job
The problem is that you have to provide the option
before: enp12s0. There might be another interface or none at all.<TBD: get the value of before>
Use the module fetch to fetch the file(s) and the filter combine to update the configuration. Then, you can synchronize the file(s) with the remote host(s). This procedure provides a robust, structured, and easily extensible framework for updating multiple netplan configuration files on multiple remote hosts in parallel.
Declare the path to netplan
and the dictionary with the updates
Running on the localhost for testing, fetch the file(s)
Take a look at the fetched file(s)
Read the configuration into the dictionary netplan_orig
gives
Update the configuration. Declare the combination of the dictionaries
gives
Update the fetched files
Take a look at the content of the file
Synchronize the file(s)
Uncomment the notify directive to apply the configuration and create the handler
Example of a complete playbook for testing