在收集的事实列表中使用 ansible 变量

Using ansible variable inside gathered fact list

我不得不从收集的事实中获取数据,使用计算数据作为查询的一部分。

我正在使用 2.9 ansible,这是我的任务

---
- hosts: ios
  connection: network_cli
  gather_facts: true
  tasks:

    - name: CEF OUTPUT
      ios_command:
        commands: sh ip cef 0.0.0.0 0.0.0.0 | i nexthop
      register: cef


    - set_fact:
        reg_result: "{{  cef.stdout |string| regex_search('Tunnel[0-9]+')}}"

    - name: IT WORKS!
      debug:
        msg: "{{ reg_result }}"

    - name: MANUAL LIST
      debug:
         var:  ansible_facts.net_interfaces.Tunnel3.description

    - name: AUTO LIST
      debug:
         var:  ansible_facts.net_interfaces.[reg_result].description

这是输出

PLAY [ios] **********************************************

TASK [Gathering Facts] **********************************
ok: [10.77.3.1]

TASK [CEF OUTPUT] ***************************************
ok: [10.77.3.1]

TASK [set_fact] *****************************************
ok: [10.77.3.1]

TASK [IT WORKS!] ****************************************
ok: [10.77.3.1] => {
    "msg": "Tunnel3"
}

TASK [MANUAL LIST] **************************************
ok: [10.77.3.1] => {
    "ansible_facts.net_interfaces.Tunnel3.description": "DMVPN via MTS"
}

TASK [AUTO LIST] ****************************************
fatal: [10.77.3.1]: FAILED! => {"msg": "template error while templating string: expected name or number. String: {{ansible_facts.net_interfaces.[reg_result].description}}"}
        to retry, use: --limit @/home/user/ansible/retry/ios_find_gw_int.retry

PLAY RECAP **********************************************
10.77.3.1                  : ok=5    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

你看。现在我知道我的默认网关指向“Tunnel3”,并且可以将这个“Tunnel3”放在 {{ ansible_facts.net_interfaces.Tunnel3.description }} 中获取一些数据,但是如何自动获取呢?而且我觉得在列表中这样的嵌套变量是一个非常方便的工具。

如果使用间接寻址,去掉点

    - name: AUTO LIST
      debug:
         var:  ansible_facts.net_interfaces[reg_result].description

Referencing key:value dictionary variables