首页 > 解决方案 > Ansible - 从清单主机名定义的变量列表中的项目列表

问题描述

我的 host_vars 中有一个名为“bonding”的变量 - 这是要聚合到 bond0 接口中的网络接口列表。这些值是在清单中定义的,并且它们在我的每个主机的变量中正确列出。

production/
├── group_vars
│   └── ipbatch.yaml
├── hosts.yaml
└── host_vars
    ├── ipbatch1.yaml
    ├── ipbatch2.yaml
    └── ipbatch3.yaml

生产/host_vars/ipbatch3.yaml的内容 :

---
bonding:
  - eno3
  - eno4

检查此变量是否正确设置:

tasks:
  - name: debug test - hostvars
    debug:
      var: hostvars[inventory_hostname]

输出提取 - 看起来正确:

        "ansible_virtualization_type": "kvm",
        "bonding": [
            "eno3",
            "eno4"
        ],
        "dns": true,
        "ftp": true,

现在,我想在一个角色中使用这个变量,这样:

  tasks:
    - set_fact:
        interface_bond: "{{ ansible_interfaces | select('match','^bond[0-9]') | sort | list | first }}"
  roles:
    - role: network
      network_ifaces:
      - device: "{{ item }}"
        bondmaster: "{{ interface_bond }}"
      with_items: "{{ hostvars[inventory_hostname][bonding] | list }}"

这是问题所在:ansible 说我的项目列表是空的。我正在尝试以这种方式调试我的变量请求:

    - debug:
        var: "{{ hostvars[inventory_hostname][bonding] | list }}"

输出是一条错误消息。但是,错误消息中会显示正确的值:

fatal: [ipbatch2]: FAILED! => {"msg": "ansible.vars.hostvars.HostVarsVars object has no element ['eno1']"}
fatal: [ipbatch1]: FAILED! => {"msg": "ansible.vars.hostvars.HostVarsVars object has no element ['eth0', 'eth1']"}
fatal: [ipbatch3]: FAILED! => {"msg": "ansible.vars.hostvars.HostVarsVars object has no element ['eno3', 'eno4']"}

我尝试过的:

var: "{{ hostvars[inventory_hostname][bonding] | list }}"
var: "{{ bonding }}"
var: "{{ bonding | list }}"
var: "{{ map('extract','hostvars[inventory_hostname]','bonding')| list }}"
var:  "{{ hostvars[inventory_hostname] | map(attribute='bonding') | list }}"
var: "{{ hostvars[inventory_hostname].bonding | list }}"

但是最近的输出,即使是错误的,也是第一行。

预期结果:with_items语句应返回以太网接口列表,如host_vars清单文件中所述

标签: ansiblejinja2ansible-inventory

解决方案


bonding是哈希中键的名称(作为字符串),而不是要用作键的 var 的名称。此外,bonding在您的 yaml 结构中已经有一个您可以直接访问的列表。在这种情况下不需要使用list过滤器。

创建循环的正确语法是以下之一:

  • with_items: "{{ hostvars[inventory_hostname]['bonding'] }}"
  • with_items: "{{ hostvars[inventory_hostname].bonding }}"

推荐阅读