如何遍历Ansible字典提取INTERFACE值并用于后续配置任务
问题:遍历Ansible字典中的INTERFACE值配置IP Helper
我有一个测试设备输出生成的字典:
{ "device_IPs": [ { "INTERFACE": "Vlan300", "IP_ADDRESS": "3.3.3.1", "PROTO": "down", "STATUS": "up" }, { "INTERFACE": "Vlan400", "IP_ADDRESS": "4.4.4.1", "PROTO": "down", "STATUS": "up" } ] }
我需要编写Ansible Playbook,提取所有INTERFACE的值,为这些VLAN接口配置IP helper。我当前的Playbook如下:
--- - name: run command and parse with textFSM hosts: switches gather_facts: no tasks: - name: show command and store in var cisco.ios.ios_command: commands: show ip interface brief | e una|Eth register: sh_ip_int_br_output - name: parse output data ansible.builtin.set_fact: device_IPs: "{{ sh_ip_int_br_output.stdout[0] | parse_cli_textfsm('testFSM_templates/ios_show_ip_int_br.textfsm') }}" - name: add ip helper to vlan cisco.ios.ios_config: lines: - ip helper-address 1.1.1.1 parents: "interface {{ each one of the INTERFACE values from dict }}"
请问如何遍历上述字典中的每个INTERFACE键,将其值存入变量并在最后一个任务中循环使用?
解决方法
在larsks和Vladimir的帮助下,问题已解决。只需在Playbook中添加以下任务即可实现需求:
- name: 提取字典列表中的接口信息 set_fact: dict_interface_info: "{{ device_IPs | map(attribute='INTERFACE') }}" - name: 配置IP helper cisco.ios.ios_config: lines: - ip helper-address 1.1.1.1 parents: "interface {{ item }}" loop: "{{ dict_interface_info }}"
实现说明
- 通过
map(attribute='INTERFACE')过滤器,从device_IPs的列表型字典中提取所有INTERFACE对应的值,生成一个接口名称列表; - 在配置IP helper的任务中,使用
loop遍历这个接口列表,为每个接口执行对应的配置命令。
内容的提问来源于stack exchange,提问作者Asher Armando
相关产品推荐
相关产品推荐

