如何在 Ansible 中执行 with_dict 的顺序?

How to enforce the order of with_dict in Ansible?

我有要遍历的字典类型的数据,保持顺序很重要:

with_dict_test:
  one:   1
  two:   2
  three: 3
  four:  4
  five:  5
  six:   6

现在当我编写打印键和值的任务时,它们以看似随机的顺序打印(6、3、1、4、5、2)。

---
- name: with_dict test
  debug: msg="{{item.key}} --> {{item.value}}"
  with_dict: with_dict_test

如何强制 Ansible 按给定顺序迭代?或者有什么比 with_dict 更适合的吗?在任务执行期间我真的需要键和值...

我没有看到使用字典的简单方法,因为它们根据其散列键的顺序确定顺序。
您可以执行以下操作:

with_dict_test:
  - { key: 'one', value: 1 }
  - { key: 'two', value: 2 }
  - { key: 'three', value: 3 }
  - { key: 'four', value: 4 }
  - { key: 'five', value: 5 }
  - { key: 'six', value: 6 }

并且在剧本中只需将 with_dict 替换为 with_items:

---
- name: with_dict test
  debug: msg="{{item.key}} --> {{item.value}}"
  with_items: with_dict_test

如果你觉得这个解决方案(变量的声明)很难看,你可以这样做:

key: ['one', 'two', 'three', 'four', 'five', 'six']
values: [1, 2, 3, 4, 5, 6]

在剧本中

---
- name: with_dict test
  debug: msg="{{item.0}} --> {{item.1}}"
  with_together:
    - key
    - value

我不太确定,但也许这会对你有所帮助:

  - hosts: localhost
    vars:
      dict:
        one: 1
        two: 2
        three: 3
      sorted: "{{ dict|dictsort(false,'value') }}"

    tasks:
      - debug:
          var: sorted
      - debug:
          msg: "good {{item.1}}"
        with_items: sorted

我假设您可以使用 Jinja 过滤器以某种方式对复数值进行排序。您可能会检查的另一件事是组合 dict.values()|listwith_sequence,但是您从那块石头中挤出的任何东西都不会尖叫 "maintainable."