【问题标题】:Iterate Over 2 dictionary in ansible在ansible中迭代2个字典
【发布时间】:2021-08-17 12:11:36
【问题描述】:

我有两本字典:

- Test1:
   1: pass
   2: fail
   3: pass

- Test2:
   1.1.1.1: val1
   2.2.2.2: val2
   3.3.3.3: val3

条件是 Test1.value contians 失败时

- name: test
  debug:
    msg: "{{item.1.value}} {{item.1.key}} {{item.0.key}} {{item.0.value}}"
  with_together:
    - "{{Test1}}"
    - "{{Test2}}"
  when: item.0.value == "fail"

这无法按预期工作,无法在一个循环中同时获取 2 dict 的键和值

【问题讨论】:

  • 我需要字典键和循环内的值

标签: ansible ansible-2.x ansible-inventory ansible-facts ansible-template


【解决方案1】:

when 语句中,您必须使用item.0item.1 来评估条件。我建议您在with_together 循环中使用列表,如果您使用变量,则必须使用大括号{{ variable }}

尝试如下:

    - name: test
      debug:
        msg: "{{item.1 }}"
      with_together:
        - "{{ Test1.values() | list }}"
        - "{{ Test2.values() | list }}"
      when: item.0 == "fail"

你会得到

TASK [test] *******************************************************************************************************************************************************************************************************
skipping: [127.0.0.1] => (item=['pass', 'val1'])
ok: [127.0.0.1] => (item=['fail', 'val2']) => {
    "msg": "val2"
}
skipping: [127.0.0.1] => (item=['pass', 'val3'])

【讨论】:

  • 在实现这一点时要格外小心,因为不能依赖 yaml/ansible/python 中的 dict 键顺序。您可能很容易以不同步的项目结束。如果您可以控制输入数据,则应将其直接转换为列表,或转换为可以轻松引用另一个的字典(例如,第二个引用的 id 可以在第一个中找到...... )
  • 我需要键和值...如果使用Test1.values,键值我不会有内部循环
  • 您没有在示例中的任何位置使用该键显示单个示例。
  • 将其添加到问题中,我尝试了这个 with_nested(使用 item[0]、item [1] 等等......)但循环运行多次迭代然后预期任何其他方法......一个是Jinja 2 模板还有其他更好的方法来做到这一点..
【解决方案2】:

我通过以下方式实现了这一点:
使用过滤器将 dict 转换为列表 -> |list
自从 两个大小相同的字典我能够在单个循环中获取两个字典的数据:

- name: test
  debug:
    msg: "{{item.0}} {{item.1}} {{item.2}} {{item.3}}"
  with_together:
    - "{{ Test1.values() | list }}"
    - "{{ Test2.values() | list }}"
    - "{{ Test1.keys() | list }}"
    - "{{ Test2.keys() | list }}"
  when: item.0 == "fail"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-05
    • 2017-09-26
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多