ansible - Ansible 循环和打印字典变量
问题描述
任何人都可以帮助解决这个基本问题吗?我有一个字典变量,我想打印它。
dict_var:
- key1: "val1"
- key2: "val2"
- key3: "val3"
是否可以在剧本中循环和打印其内容?
解决方案
Q: "Loop and print variable's content."
A: The variable dict_var is a list. Loop the list, for example
- hosts: localhost
vars:
dict_var:
- key1: "val1"
- key2: "val2"
- key3: "val3"
tasks:
- debug:
var: item
loop: "{{ dict_var }}"
gives (abridged)
"item": {
"key1": "val1"
}
"item": {
"key2": "val2"
}
"item": {
"key3": "val3"
}
Q: "Loop and print dictionary."
A: There are more options when the variable is a dictionary. For example, use dict2items to "loop and have key pair values in variables" item.key and item.value
- hosts: localhost
vars:
dict_var:
key1: "val1"
key2: "val2"
key3: "val3"
tasks:
- debug:
var: item
loop: "{{ dict_var|dict2items }}"
gives (abridged)
"item": {
"key": "key1",
"value": "val1"
}
"item": {
"key": "key2",
"value": "val2"
}
"item": {
"key": "key3",
"value": "val3"
}
The next option is to loop the list of the dictionary's keys. For example
- debug:
msg: "{{ item }} {{ dict_var[item] }}"
loop: "{{ dict_var.keys()|list }}"
gives (abridged)
"msg": "key1 val1"
"msg": "key2 val2"
"msg": "key3 val3"
推荐阅读
- android - 在android studio中显示和隐藏栏的稳定视图
- python - 'str' 对象不能解释为文本抓取方法中的整数错误
- reactjs - 如何在 React 项目中集成 chrome 铸造
- c# - 有没有办法忽略asp.net核心中的特定属性包含多对多关系的函数
- ubuntu - 配置:错误:远程访问需要 curl。安装 curl 或使用 --disable-dap 构建
- mysql - Laravel InsertOrIgnore - 插入了哪些记录?
- python - discord.py 等待 channel.connect 超时
- ionic-framework - 离子原生闪屏 vs 电容闪屏?
- python - 如何显示通过 aiortc 接收的流而不写入文件
- python - 如何在带有美丽汤的类中找到标签