ansible嵌套循环,外循环作为字典,内循环作为字典项的值

ansible nested loops with outerloop as dict and inner loop as value of dict items

我有 ansible 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 但没用

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

---
- 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