在Ansible Playbook的嵌套循环中循环遍历词典列表

时间:2020-10-21 19:25:29

标签: dictionary ansible nested-loops

我需要在嵌套循环中的另一组词典列表上遍历词典列表,以读取我得到的输出中的所有值。我是ansible的新手,也尝试过with_items,循环,with_subelements和with_nested。没有任何必要满足我从输出中读取所有值的需要。有人可以阐明这个我们如何做嵌套循环的方法吗?非常感谢您的帮助。

Outer-List: [    
  { 
     Key1: value1
     Key2: value2          
     Inner-List: [ 
        {
            Key31: value-A
            Key32: value-B
        }
        {
            Key33: value-C
            Key34: value-D
        }
     ],
  },              ====> OuterList[0] ends here
  {               ====> OuterList[1] starts here
     Key1: value1
     Key2: value2
     Inner-List: [       
        {
            Key31: value-E
            Key32: value-F
        }
        {
            Key33: value-G
            Key34: value-H
        }
     ],
   }              ====> OuterList[1] ends here
]                 ====> OuterList ends here

1 个答案:

答案 0 :(得分:0)

Q:在字典列表上方。

A:给定有效的YAML和有效的Ansible variable

Outer_List:
  - Inner-List: 
      - Key31: value-A
        Key32: value-B
      - Key33: value-C
        Key34: value-D
    Key1: value1
    Key2: value2
  - Inner-List: 
      - Key31: value-E
        Key32: value-F
      - Key33: value-G
        Key34: value-H
    Key1: value1
    Key2: value2

使用subelements。例如,下面的任务

    - debug:
        msg: "{{ item.0.Key1 }} {{ item.0.Key2 }} {{ item.1 }}"
      with_subelements:
        - "{{ Outer_List }}"
        - Inner-List

给予(删节)

  msg: 'value1 value2 {''Key31'': ''value-A'', ''Key32'': ''value-B''}'
  msg: 'value1 value2 {''Key33'': ''value-C'', ''Key34'': ''value-D''}'
  msg: 'value1 value2 {''Key31'': ''value-E'', ''Key32'': ''value-F''}'
  msg: 'value1 value2 {''Key33'': ''value-G'', ''Key34'': ''value-H''}'

下面的JSON是有效的

{
"Outer_List":
    [
        {
            "Inner-List": [
                {
                    "Key31": "value-A",
                    "Key32": "value-B"
                },
                {
                    "Key33": "value-C",
                    "Key34": "value-D"
                }
            ],
            "Key1": "value1",
            "Key2": "value2"
        },
        {
            "Inner-List": [
                {
                    "Key31": "value-E",
                    "Key32": "value-F"
                },
                {
                    "Key33": "value-G",
                    "Key34": "value-H"
                }
            ],
            "Key1": "value1",
            "Key2": "value2"
        }
    ]
}