ansible嵌套循环,将outerloop作为dict,将内部循环作为dict项的值

问题描述 投票:1回答:1

我有ansible dict,其中key是名称,value是整数值。我希望我的外部循环遍历dict然后内部循环迭代该值的次数。

- hosts: localhost
  tasks:
  - debug: msg="region {{ item.key }} value {{ item.value }}"
    with_subelements:
      - "{{ objs }}"
      - "{{ item.value }}"
  vars:
    objs:
      amrs: 3
      apac: 1
      emea: 2

所以输出应该是

region amrs value 1
region amrs value 2
region amrs value 3
region apac value 1
region emea value 1
region emea value 2

我想知道以上是否可以通过ansible实现。我也尝试过with_nested但是没有用

ansible ansible-playbook ansible-2.x
1个回答
0
投票

您可以使用帮助程序任务来生成序列:

---
- hosts: localhost
  gather_facts: yes
  vars:
    objs:
      amrs: 3
      apac: 1
      emea: 2
  tasks:
    - set_fact:
        tmp_list: "{{ tmp_list | default([]) + [dict(name=item.key,seq=lookup('sequence','count='+item.value|string,wantlist=true))] }}"
      with_dict: "{{ objs }}"
    - debug: msg="region {{ item.0.name }} value {{ item.1 }}"
      with_subelements:
        - "{{ tmp_list }}"
        - seq
© www.soinside.com 2019 - 2024. All rights reserved.