问题
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'
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}}'
How do I do that? I tried
aValue: '{{config[num].a}}'
but got an error: 'dict object' has no attribute u'1'
aValue: '{{config["num"].a}}'
but got an error: 'dict object' has no attribute 'num'
回答1:
If you quote those config keys, they will become strings:
config:
"0":
a: true
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}'
to cause ansible to parse --extra-vars
as JSON, where "num"
really will be a Number
(in the JSON sense)
or coerce num
in the jinja2 expression:
aValue: '{{ config[ (num|int) ].a }}'
来源:https://stackoverflow.com/questions/53294414/ansible-dictionary-key-as-variable