Ansible 字典键作为变量 [英] Ansible dictionary key as variable

查看:47
本文介绍了Ansible 字典键作为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们在角色 defaults/main.yml 中有这样的东西:

编号:0配置:0:答:真的乙:'x'1:答:假的经过'2:答:假的乙:'z'

现在我在 playbook 调用中发送 -e num=1,我想在某处使用基于此值的值 ab角色中的其他角色,例如:

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'

解决方案

如果你引用那些配置键,它们将变成字符串:

配置:0":答:真的

或者,如果您的剧本的其余部分确实希望它们是数字,则可以通过两种方式使 num 实际上成为数字:

ansible -e '{"num": 1}' 使 ansible 将 --extra-vars 解析为 JSON,其中 "num" 真的会是一个 Number(在 JSON 意义上)

或在jinja2表达式中强制num:

aValue: '{{ config[ (num|int) ].a }}'

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'

解决方案

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 }}'

这篇关于Ansible 字典键作为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆