我有一个ansible
角色
- 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
以及处理该事件的处理程序
- name: restart vlan interfaces
command: bash -c "ifdown {{ item.device }} && ifup {{ item.device}}"
with_items: "{{ vlan_interfaces }}"
但我不想启动和停止所有的接口,只想启动和停止那些实际发生变化的接口。
有没有办法只将“item.device”推送到我可以在处理程序中使用的列表,或者有没有办法让处理程序在每个项目上运行?
答案1
因此,您无法在剧本上执行特定操作来处理 with-items 任务中的每个调用。但您确实会获得可以注册的结果,然后在处理程序中执行操作。
因此将“注册”命令添加到任务中
- 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
并在处理程序中循环遍历它。因为输出如下所示:
"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
},
...
]
您可以检查每个结果中的“更改”状态,并且仅重新启动那些:
- 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 }}"