【问题标题】:Ansible loop over list of dictionaries and individual dictionariesAnsible 循环遍历字典列表和单个字典
【发布时间】:2021-06-11 21:00:47
【问题描述】:

我想遍历字典列表以及其他字典。它们都具有相同的架构。

  - set_fact:
      my_list:
        - { foo: 1, bar: 2, baz: 3 }
        - { foo: 4, bar: 5, baz: 6 }
        - { foo: 7, bar: 8, baz: 9 }

  - debug:
      msg: "{{item.foo}} {{item.bar}} {{item.baz}}"
    loop:
      - "{{ my_list }}"
      - { foo: 10, bar: 11, baz: 12 }
      - { foo: 13, bar: 14, baz: 15 }

但这给出了:

失败了! => {"msg": "该任务包含一个带有未定义变量的选项。错误是:'list object' has no attribute 'foo'

我该怎么做?

【问题讨论】:

    标签: loops dictionary ansible yaml jinja2


    【解决方案1】:

    连接列表,例如

        - debug:
            msg: "{{ item.foo }} {{ item.bar }} {{ item.baz }}"
          loop: "{{ my_list +
                    [{'foo': 10, 'bar': 11, 'baz': 12}] +
                    [{'foo': 13, 'bar': 14, 'baz': 15}] }}"
    

    给予

      msg: 1 2 3
      msg: 4 5 6
      msg: 7 8 9
      msg: 10 11 12
      msg: 13 14 15
    

    下面的 YAML 格式给出了相同的结果

        - debug:
            msg: "{{ item.foo }} {{ item.bar }} {{ item.baz }}"
          loop: "{{ my_list + _list2 + _list3 }}"
          vars:
            _list2:
              - foo: 10
                bar: 11
                baz: 12
            _list3:
              - foo: 13
                bar: 14
                baz: 15
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-04
      • 2014-06-27
      • 1970-01-01
      相关资源
      最近更新 更多