如何循环任务,每个任务都有另一个循环

时间:2019-07-30 07:19:30

标签: ansible nested-loops

我想在每个任务中在var_1上循环几个任务,在每个任务中在var_2上循环。

我试图在此处使用include_tasks,但不确定是否有更好的方法。

我可能错过了语法,或者整个逻辑是错误的。我收到此错误: 错误! include_tasks的无效选项:type_name,type_attr

关于如何获得所需输出的任何建议?

vars:
 var_1:
  - name: bla1
    attributes:
     - a
     - b
  - name: bla2
    attributes:
     - c
     - d
 var_2:
  - type: typ1
    typ_attr:
     - aa
     - bb
  - type: typ2
    typ_attr:
     - cc
     - dd

   #main.yml

    tasks:
      - include_tasks: supporting.yml type_name={{item.0.type}} type_attr = {{item.1}}
        loop: "{{ var_2|subelements('typ_attr') }}"

#supporting.yml

    - debug:
        msg: "name = {{item.0.name}}; nameattr = {{item.1}}; type = {{type_name}}; typeattr = {{type_attr}}
      loop: "{{var_1|subelements('attributes')}}"

所需的输出:

name = bla1; nameattr = a;类型= typ1; typeattr = aa

name = bla1; nameattr = a;类型= typ1; typeattr = bb

name = bla1; nameattr = a;类型= typ2; typeattr = cc

name = bla1; nameattr = a;类型= typ2; typeattr = dd

name = bla1; nameattr = b;类型= typ1; typeattr = aa

name = bla1; nameattr = b;类型= typ1; typeattr = bb

name = bla1; nameattr = b;类型= typ2; typeattr = cc

name = bla1; nameattr = b;类型= typ2; typeattr = dd

name = bla2; nameattr = c;类型= typ1; typeattr = aa

name = bla2; nameattr = c;类型= typ1; typeattr = bb

name = bla2; nameattr = c;类型= typ2; typeattr = cc

name = bla2; nameattr = c;类型= typ2; typeattr = dd

name = bla2; nameattr = d;类型= typ1; typeattr = aa

name = bla2; nameattr = d;类型= typ1; typeattr = bb

name = bla2; nameattr = d;类型= typ2; typeattr = cc

name = bla2; nameattr = d;类型= typ2; typeattr = dd

1 个答案:

答案 0 :(得分:1)

有必要在所包含任务的循环内使用不同的 loop_var 。下面的任务完成了工作。

- include_tasks: supporting.yml
  loop: "{{ var_2|subelements('typ_attr') }}"

$ cat supporting.yml
- debug:
    msg: "name = {{ item1.0.name }};
          nameattr = {{ item1.1 }};
          type = {{ item.0.type }};
          typeattr = {{ item.1 }}"
  loop: "{{ var_1|subelements('attributes') }}"
  loop_control:
    loop_var: item1