如何在Ansible中一起使用loop和with_nested

时间:2019-05-18 15:25:48

标签: ansible nested-loops

我定义了这样的vars-

  vars:
    values:
      - key1: value1 
        key2:
          - value1.1
          - value1.2

      - key1: value2 
        key2: 
          - value2.1
          - value2.2

要在key1上迭代key2中的相应值

我正在使用python 2.7.10运行ansible 2.7.10。这是根据在网上找到的一些建议在任务中写的内容-

(与_subelements一起使用)

- name: test loops
  debug:
    msg: "This is key1: {{ item.0.key1 }}, and here is corresponding key2 element {{ item.1 }}"
  with_subelements:
    - values
    - key2

预期输出:

This is key1: value1, and here is corresponding key2 element value1.1
This is key1: value1, and here is corresponding key2 element value1.2
This is key1: value2, and here is corresponding key2 element value2.1
This is key1: value2, and here is corresponding key2 element value2.2

执行剧本时出现错误:

致命:[localhost]:失败! => {“ msg”:“子元素查找需要字典,得到了'值'”}

任何想法如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

正确的语法是

with_subelements:
  - "{{ values }}"
  - key2

Migrated from with_X to loop

loop: "{{ values|subelements('key2') }}"

下面的戏

- hosts: localhost
  vars:
    values:
      - key1: value1
        key2:
          - value1.1
          - value1.2
      - key1: value2 
        key2: 
          - value2.1
          - value2.2
  tasks:
    - debug:
        msg: "{{ item.0.key1 }} - {{ item.1 }}"
      with_subelements:
        - "{{ values }}"
        - key2

给予(节略):

"msg": "value1 - value1.1"
"msg": "value1 - value1.2"
"msg": "value2 - value2.1"
"msg": "value2 - value2.2"