Ansible dictionary key as variable

两盒软妹~` 提交于 2020-03-01 07:19:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!