如何在ansible模板中获取嵌套变量?

How to fetch nested variable in ansible template?

如何获取嵌套如下的变量:

mongoservers:
- mongo_master: dev_01
  label: mongomaster dev01
  urls:
    - mongomaster01.dev.local.net
    - mongomaster02.dev.local.net
- mongo_master: dev_02
  label: mongomaster dev02
  urls:
    - mongomaster.dev03.local.net
    - mongomaster.dev04.local.net

我想从上面的 yaml 中访问变量中的 url 我的条件是如果 mongoservers.mongo_masterdev01 我想获取属于它的所有 url。

您可以使用 json_query. Read the jmespath doc 过滤和查询哈希列表以了解查询语言

在以下示例剧本中,我使用了以下查询:

[?mongo_master=='dev_01'].urls[]

可以解释为

For every element in the incoming list having a mongo_master element equal to dev_01, select the urls element inside it and finally flatten the list

这是完整的示例剧本:

---
- name: Filter list
  hosts: localhost
  gather_facts: false

  vars:
    mongoservers:
    - mongo_master: dev_01
      label: mongomaster dev01
      urls:
        - mongomaster01.dev.local.net
        - mongomaster02.dev.local.net
    - mongo_master: dev_02
      label: mongomaster dev02
      urls:
        - mongomaster.dev03.local.net
        - mongomaster.dev04.local.net

  tasks:
    - name: filter
      vars:
        query: >-
          [?mongo_master=='dev_01'].urls[]
      debug:
        msg: "{{ mongoservers | json_query(query) | list }}"

给出:

PLAY [Filter list] ********************************************************************************************************************************************************************************************************

TASK [filter] *************************************************************************************************************************************************************************************************************
Wednesday 25 September 2019  17:57:39 +0200 (0:00:00.039)       0:00:00.039 *** 
ok: [localhost] => {
    "msg": [
        "mongomaster01.dev.local.net",
        "mongomaster02.dev.local.net"
    ]
}

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