Restarting network interfaces that have changed with ansible
So, you can't really do something specific on the playbook to handle each call in the with-items tasks. But you do get results that you can register and then do stuff with in the handler.
so add the "register" command to the task
- name: add virtual interface configs for vlan
template: src=ifcfg-eth.vlan.j2 dest=/etc/sysconfig/network-scripts/ifcfg-{{ item.device }}
with_items: "{{ vlan_interfaces }}"
tags: firewall_d-public-network-vlans
register: add_virtual_interface_output
notify: restart vlan interfaces
and loop through it in the handler. Because output looks like this:
"results": [
{
"_ansible_notify": [
"restart vlan interfaces"
],
"changed": false,
"gid": 0,
"group": "root",
"item": {
"device": "eth1.405",
"ipaddr": "172.16.55.5",
"lladr": "00:50:56:ab:5d:7c",
"network": "172.16.55.0",
"prefix": 24
},
"mode": "0644",
"owner": "root",
"path": "/etc/sysconfig/network-scripts/ifcfg-eth1.405",
"secontext": "system_u:object_r:net_conf_t:s0",
"size": 100,
"state": "file",
"uid": 0
},
...
]
you can check for the "changed" state in each result, and only restart those:
- name: restart vlan interfaces
# debug : msg="{{ item.changed }}"
command: bash -c "ifdown {{ item.item.device }} && ifup {{ item.item.device }}"
when: item.changed == true
with_items: "{{ add_virtual_interface_output.results }}"
Related videos on Youtube
![Peter Turner](https://i.stack.imgur.com/Lhaux.png?s=256&g=1)
Peter Turner
Faithful Catholic - Father of 5, Husband of 1 Programmer of cloudish things from Southern Wisconsin.
Updated on September 18, 2022Comments
-
Peter Turner almost 2 years
I've got an
ansible
role that- name: add virtual interface configs for vlan template: src=ifcfg-eth.vlan.j2 dest=/etc/sysconfig/network-scripts/ifcfg-{{ item.device }} with_items: "{{ vlan_interfaces }}" tags: firewall_d-public-network-vlans notify: restart vlan interfaces
and a handler that handles it
- name: restart vlan interfaces command: bash -c "ifdown {{ item.device }} && ifup {{ item.device}}" with_items: "{{ vlan_interfaces }}"
But I don't want to start and stop all the interfaces, only the ones that have actually changed.
Is there a way to only push "item.device" to a list I can use in the handler or is there a way to make a handlers to run on each item?