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

标签 loops 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更适合的吗? ?在任务执行期间我真的需要键和值...

最佳答案

我没有看到使用 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 }

在剧本中只需替换 with_dictwith_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

关于loops - 如何在 Ansible 中强制执行 with_dict 的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28414055/

相关文章:

windows - 如何使用批处理脚本对目录中的每个文件执行某些操作

Ansible:使用变量定义 playbook 主机

mysql - 如何从ansible play中的shell命令中提取文件名

node.js - ansible 安装 node.js 版本 6

python - 在循环中更改模型对象名称 : python & sklearn

c++ - 在特定时间运行 C++ 循环

java - 在HashTable中查找Key的方法

mysql - mysql 将多行插入单行

docker - 通过Docker运行Ansible时最优雅的方式来处理ANSIBLE_VAULT_PASSWORD_FILE?

yaml - ansible with_items 列表列表正在变平