gpt4 book ai didi

dictionary - ansible with_dict 在提供 set_fact 变量时失败

转载 作者:行者123 更新时间:2023-12-05 07:27:53 25 4
gpt4 key购买 nike

我正在尝试为接口(interface)变量动态提供字典名称。

我的 ansible 任务看起来像这样。

- 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 需要一个字典"}但是当我提供 with_dict: {{ h1_interfaces }} 时,它就像一个魅力。我做错了什么?

最佳答案

显然你也有一个变量 host_name,它被设置为 h1h2,你想访问字典: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"
}

干杯

关于dictionary - ansible with_dict 在提供 set_fact 变量时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53710459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com