This question already has an answer here:
这个问题在这里已有答案:
- How can I use Ansible nested variable? 1 answer
我如何使用Ansible嵌套变量? 1个答案
My question looks trivial but I already spend some hours on it.
我的问题看起来微不足道,但我已经花了几个小时。
How to dynamically navigate into a json variable, with jinja2. ex: I get
如何使用jinja2动态导航到json变量。例如:我明白了
ansible_lvm.vgs:
"vgs": {
"vgdata": {
"free_g": "16",
"size_g": "0"
},
"vgswap": {
"free_g": "0",
"size_g": "00"
}
}
In a jinja2 structure I would like to get "free_g" attribut for "vgdata": None of the code hereafter works:
在jinja2结构中,我想得到“free_g”attribut for“vgdata”:以后的代码都不起作用:
{% set my_vg_name = 'vg_data' %}
{% set my_vg_size = ansible_lvm.vgs.(my_vg_name).free_g %}
{% set my_vg_size = ansible_lvm.vgs.{{my_vg_name}}.free_g %}
{% set my_vg_size = ansible_lvm.vgs|selectattr(my_vg_name, 'free_g') %}
Thanks for your help,
谢谢你的帮助,
1 个解决方案
#1
0
So, I hope that code snippet at the top is just an example, and not really what you are using, since it's malformed JSON. And I hope you are not actually asking the vgs
object for vg_data
when the key is vgdata
, because that will never end well.
所以,我希望顶部的代码片段只是一个例子,而不是你正在使用的代码片段,因为它是错误的JSON。并且我希望当密钥是vgdata时,你实际上并没有要求vg_data的vgs对象,因为它永远不会结束。
That aside:
You access dict
objects in python using vgs[my_vg_name]
syntax, or if you aren't sure that vgs
contains that key, vgs.get(my_vg_name, {})
to provide an empty dict
as the default if vgs
does not contain a key whose value is in the my_vg_name
variable.
您可以使用vgs [my_vg_name]语法在python中访问dict对象,或者如果您不确定vgs是否包含该密钥,则vgs.get(my_vg_name,{})如果vgs不包含密钥则提供空dict作为默认值其值在my_vg_name变量中。
Perhaps it's just a bad question, but if you always want vgdata.free_g
then why the dynamic access at all?
也许这只是一个糟糕的问题,但如果你总是想要vgdata.free_g那么为什么动态访问呢?
#1
0
So, I hope that code snippet at the top is just an example, and not really what you are using, since it's malformed JSON. And I hope you are not actually asking the vgs
object for vg_data
when the key is vgdata
, because that will never end well.
所以,我希望顶部的代码片段只是一个例子,而不是你正在使用的代码片段,因为它是错误的JSON。并且我希望当密钥是vgdata时,你实际上并没有要求vg_data的vgs对象,因为它永远不会结束。
That aside:
You access dict
objects in python using vgs[my_vg_name]
syntax, or if you aren't sure that vgs
contains that key, vgs.get(my_vg_name, {})
to provide an empty dict
as the default if vgs
does not contain a key whose value is in the my_vg_name
variable.
您可以使用vgs [my_vg_name]语法在python中访问dict对象,或者如果您不确定vgs是否包含该密钥,则vgs.get(my_vg_name,{})如果vgs不包含密钥则提供空dict作为默认值其值在my_vg_name变量中。
Perhaps it's just a bad question, but if you always want vgdata.free_g
then why the dynamic access at all?
也许这只是一个糟糕的问题,但如果你总是想要vgdata.free_g那么为什么动态访问呢?