Reputation: 520
I would like to change DNS IP address from 192.168.86.14 to 192.168.86.16 in Ubuntu netplan yaml file:
link: ens3
addresses: [192.168.86.12/24]
gateway4: 192.168.86.1
nameservers:
addresses: [192.168.86.14,8.8.8.8,8.8.4.4]
Here is my ansible playbook:
- name: test
ansible.builtin.replace:
path: /etc/netplan/00-installer-config.yaml
regexp: '(addresses: \[)+192.168.86.14,'
replace: '\1192.168.86.16,'
My playbook doesn't change anything in the file. Tried to escape comma but doesn't match anything as well.
For some reason I need to make sure the IP address is between "addresses [" and "," so I can't just use the syntax like this :
- name: test
ansible.builtin.replace:
path: /etc/netplan/00-installer-config.yaml
regexp: '192.168.86.14'
replace: '192.168.86.16'
I am very new to Ansible, any help is appreciated!
Upvotes: 3
Views: 3146
Reputation: 67984
The dictionaries are immutable in YAML. But, you can update dictionaries in Jinja2. Let's take a complete example of a netplan configuration file, e.g.
shell> cat 00-installer-config.yaml
network:
version: 2
renderer: networkd
ethernets:
ens3:
mtu: 9000
enp3s0:
link: ens3
addresses: [192.168.86.12/24]
gateway4: 192.168.86.1
nameservers:
addresses: [192.168.86.14,8.8.8.8,8.8.4.4]
Read the dictionary into a variable
- include_vars:
file: 00-installer-config.yaml
name: netplan_conf
gives
netplan_conf:
network:
ethernets:
enp3s0:
addresses:
- 192.168.86.12/24
gateway4: 192.168.86.1
link: ens3
nameservers:
addresses:
- 192.168.86.14
- 8.8.8.8
- 8.8.4.4
ens3:
mtu: 9000
renderer: networkd
version: 2
Create a template that updates the nameservers
shell> cat 00-installer-config.yaml.j2
{% set _dummy = netplan_conf.network.ethernets.enp3s0.nameservers.update({'addresses': _addresses}) %}
{{ netplan_conf|to_nice_yaml }}
The task below
- template:
src: 00-installer-config.yaml.j2
dest: 00-installer-config.yaml
vars:
_addresses: "{{ netplan_conf.network.ethernets.enp3s0.nameservers.addresses|
regex_replace('192.168.86.14', '192.168.86.16') }}"
will update the configuration file
shell> cat 00-installer-config.yaml
network:
ethernets:
enp3s0:
addresses:
- 192.168.86.12/24
gateway4: 192.168.86.1
link: ens3
nameservers:
addresses:
- 192.168.86.16
- 8.8.8.8
- 8.8.4.4
ens3:
mtu: 9000
renderer: networkd
version: 2
Upvotes: 4