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

dok*_*par 7 loops ansible

我有字典类型的数据,我想迭代并保持顺序很重要:

with_dict_test:
  one:   1
  two:   2
  three: 3
  four:  4
  five:  5
  six:   6
Run Code Online (Sandbox Code Playgroud)

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

---
- name: with_dict test
  debug: msg="{{item.key}} --> {{item.value}}"
  with_dict: with_dict_test
Run Code Online (Sandbox Code Playgroud)

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

Seb*_*ler 10

我没有看到使用dicts的简单方法,因为他们根据哈希键的顺序确定顺序.
您可以执行以下操作:

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 }
Run Code Online (Sandbox Code Playgroud)

在剧本中只需替换with_dictwith_items:

---
- name: with_dict test
  debug: msg="{{item.key}} --> {{item.value}}"
  with_items: with_dict_test
Run Code Online (Sandbox Code Playgroud)

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

key: ['one', 'two', 'three', 'four', 'five', 'six']
values: [1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

并在剧本中

---
- name: with_dict test
  debug: msg="{{item.0}} --> {{item.1}}"
  with_together:
    - key
    - value
Run Code Online (Sandbox Code Playgroud)