【问题标题】:ansible nested loops with outerloop as dict and inner loop as value of dict itemsansible 嵌套循环,其中外循环作为 dict,内循环作为 dict 项的值
【发布时间】:2016-12-09 10:27:15
【问题描述】:

我有 ansible dict,其中键是名称,值是整数值。我希望我的外循环遍历 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】:

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

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

    【讨论】:

    • 你能详细解释一下 tmp_list 行吗?成功了
    • 我们遍历原始 objs dict 并从空列表开始增长 tmp_list 添加 dict 元素并将 name 设置为原始 dict 的键和 seq - 生成的序列(列表),其中的数字来自1 到原始字典的值。
    • 太棒了,你是冠军队友!
    猜你喜欢
    • 2020-03-12
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 2021-09-14
    • 1970-01-01
    相关资源
    最近更新 更多