我正在尝试为接口变量动态提供字典名称。
我的艰巨任务看起来像这样。
- name: Setting interface list
set_fact:
one_fact: "{{ host_name }}_interfaces"
- name: deb
debug: var={{ one_fact }}
- name: Managing Interfaces
ios_interface:
enabled: "{{ item['value']['enabled'] }}"
name: "{{ item['key'] }}"
state: "{{ item['value']['state'] }}"
with_dict: "{{ one_fact }}"
字典看起来像这样
---
h1_interfaces:
Ethernet1/1:
description: Firewall
enabled: true
speed: auto
state: present
Ethernet1/2:
description: asd
enabled: true
speed: auto
state: present
h2_interfaces:
Ethernet1/1:
description: Firewall
enabled: true
speed: auto
state: present
Ethernet1/2:
description: asd
enabled: true
speed: auto
state: present
设置with_dict: {{ one_fact }}
时出现错误FAILED! => {"msg": "with_dict expects a dict"}
但是当我提供with_dict: {{ h1_interfaces }}
时,它就像是一种魅力。我在做什么错了?
答案 0 :(得分:0)
显然您也有一个变量host_name
,它被设置为h1
或h2
,并且您想访问字典:h1_interfaces
/ h2_interfaces
要动态构造变量名并访问其值,应使用lookup plugin,请参见以下任务:
- name: Setting interface list
set_fact:
one_fact: "{{ lookup('vars', myvar + '_interfaces') }}"
vars:
myvar: "{{ host_name }}"
和稍作改动的剧本以证明结果:
剧本:
---
- hosts: localhost
gather_facts: false
vars:
host_name: h1
h1_interfaces:
Ethernet1/1:
description: Firewall
enabled: true
speed: auto
state: present
Ethernet1/2:
description: asd
enabled: true
speed: auto
state: present
h2_interfaces:
Ethernet1/1:
description: Firewall
enabled: true
speed: auto
state: present
Ethernet1/2:
description: asd
enabled: true
speed: auto
state: present
tasks:
- name: Setting interface list
set_fact:
one_fact: "{{ lookup('vars', myvar + '_interfaces') }}"
vars:
myvar: "{{ host_name }}"
- name: deb
debug: var=one_fact
- name: Managing Interfaces
debug:
msg: "enabled: {{ item['value']['enabled'] }}, name: {{ item['key'] }}, state: {{ item['value']['state'] }}"
with_dict: "{{ one_fact }}"
结果:
TASK [Managing Interfaces] *********************************************************************************************************************************************************************************************
ok: [localhost] => (item={'key': 'Ethernet1/1', 'value': {'description': 'Firewall', 'enabled': True, 'speed': 'auto', 'state': 'present'}}) => {
"msg": "enabled: True, name: Ethernet1/1, state: present"
}
ok: [localhost] => (item={'key': 'Ethernet1/2', 'value': {'description': 'asd', 'enabled': True, 'speed': 'auto', 'state': 'present'}}) => {
"msg": "enabled: True, name: Ethernet1/2, state: present"
}
欢呼