在 Ansible 中访问嵌套变量

Accessing nested variables in Ansible

假设我在 group_vars:

中定义了这个
ucarp_data:
  - vhid: 6
    interface: eth0
    hosts:
      - 10.1.60.4
      - 10.1.60.5
    options: --shutdown --preempt

  - vhid: 9
    interface: eth0
    hosts:
      - 10.1.60.7
      - 10.1.60.8
    options: --shutdown --preempt

我想检查我当前 运行 所针对的主机是否在此 hosts: 数组中。

类似于:

- name: Check if ucarp_data contains this host
  assert:
    that: ansible_host in ucarp_data.hosts

但是这个returnsfatal: [test_machine]: FAILED! => {"msg": "The conditional check 'ansible_host in ucarp_data.hosts' failed. The error was: error while evaluating conditional (ansible_host in ucarp_data.hosts): 'dict object' has no attribute 'hosts'"

有什么想法吗?

此外,我一直在使用 Ansible 和嵌套的 yaml 变量来解决这些障碍...我似乎无法像在 Jupyter Notebook 中那样进行动态探索我在任何 Python 对象上都有制表符补全帮助很大,有什么建议吗?

例如,给定列表 ucarp_data,下面的剧本

- hosts: 10.1.60.5,10.1.60.7,10.1.60.9
  tasks:
    - assert:
        that: inventory_hostname in ucarp_data|map(attribute='hosts')|flatten
        fail_msg: "[ERR] {{ inventory_hostname }} not in ucarp_data"

给出(删节)

ok: [10.1.60.5] => changed=false 
  msg: All assertions passed
ok: [10.1.60.7] => changed=false 
  msg: All assertions passed
fatal: [10.1.60.9]: FAILED! => changed=false 
  assertion: inventory_hostname in ucarp_data|map(attribute='hosts')|flatten
  evaluated_to: false
  msg: '[ERR] 10.1.60.9 not in ucarp_data'