Ansible字典键作为变量 [英] Ansible dictionary key as variable
问题描述
让我们在defaults/main.yml角色中有类似的内容:
Let's have something like this in role defaults/main.yml:
num: 0
config:
0:
a: true
b: 'x'
1:
a: false
b: 'y'
2:
a: false
b: 'z'
现在,我在剧本调用中发送-e num=1
,并且我想根据角色中其他位置的值使用a
和b
值,例如:
Now I send -e num=1
in playbook call, and I want to use values a
and b
based on this value somewhere else in the role, something like:
aValue: '{{config[num].a}}'
bValue: '{{config[num].b}}'
我该怎么做?我尝试过
aValue: '{{config[num].a}}'
但出现错误:'dict object' has no attribute u'1'
aValue: '{{config["num"].a}}'
但出现错误:'dict object' has no attribute 'num'
推荐答案
如果引用这些配置键,它们将变成字符串:
If you quote those config keys, they will become strings:
config:
"0":
a: true
或者,如果您的剧本的其余部分确实希望它们成为数字,则可以通过两种方式使num
实际上成为数字:
Or, if you have the rest of your playbook that really does want them to be numbers, you can make num
actually be a number in two ways:
ansible -e '{"num": 1}'
导致ansible将--extra-vars
解析为JSON,其中"num"
实际上将是Number
(在JSON的意义上)
ansible -e '{"num": 1}'
to cause ansible to parse --extra-vars
as JSON, where "num"
really will be a Number
(in the JSON sense)
或强制num
:
aValue: '{{ config[ (num|int) ].a }}'
这篇关于Ansible字典键作为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!