是否可以在dict键中使用破折号? [英] Are dashes allowed in dict keys in ansible?
问题描述
我对剧本有疑问,想知道问题是否在于我使用的字典中的某些键名中带有破折号.无论是否允许,Ansible尚不清楚.
I have an issue with a playbook, and wonder if the issue is that some key names in the dictionary I use have a dash in them. Ansible is not clear wether this is allowed or not.
我正在使用nmstatectl获取一个描述RHEL8主机上当前网络配置的json.json输出使用其中带有破折号的键,我想几乎照原样使用输出.
I am using nmstatectl to get a json that describes the current network config on a RHEL8 host. The json output uses keys that have a dash in them, and I would like to use the output pretty much as is.
剧本:
- name: check static route using nmstatectl
hosts: rhv
tasks:
- name: collect network config
command:
cmd: nmstatectl show --json
register: nmstate
changed_when: false
- name: set fact with block storage route config
set_fact:
block_storage_route: "{{ nmstate.stdout | from_json | json_query(query) }}"
vars:
query: "routes.config[?destination == '{{ block_storage_cidr }}' ]"
- debug:
var: block_storage_route
- debug:
var: block_storage_route[0].destination
- debug:
var: block_storage_route[0].table-id
输出:
...
TASK [debug] ************************************************************************************************************************
ok: [one.example.com] => {
"block_storage_route": [
{
"destination": "10.201.142.0/24",
"metric": 301,
"next-hop-address": "10.123.231.161",
"next-hop-interface": "bond0.1161",
"table-id": 0
}
]
}
TASK [debug] ************************************************************************************************************************
ok: [one.example.com] => {
"block_storage_route[0].destination": "10.201.142.0/24"
}
TASK [debug] ************************************************************************************************************************
ok: [one.example.com] => {
"block_storage_route[0].table-id": "VARIABLE IS NOT DEFINED!"
}
如您所见,我得到一个未定义变量"错误.即使键"table-id"仍然存在,存在...为什么?
As you can see I get a "VARIABLE IS NOT DEFINED" error. That even though the key "table-id" is present... Why?
推荐答案
Q:" Ansible词典中的键中是否允许使用破折号?"
Q: "Are dashes allowed in dictionary keys in Ansible?"
A:是的.他们是.实际上,YAML对密钥没有任何限制.引用自映射(又名Python字典)
A: Yes. They are. In fact, there are no restrictions in YAML on the keys. Quoting from Mapping (aka Python dictionary)
"映射节点的内容是无序的一组键:值节点对,但每个键都是唯一的.YAML对节点没有进一步的限制.特别是,键可以是任意节点,...''
Use bracket notation instead of the dot notation when the name of the key doesn't comply with Ansible Creating valid variable names
- debug:
var: block_storage_route[0]['table-id']
这篇关于是否可以在dict键中使用破折号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!