是否可以在dict键中使用破折号?

编程入门 行业动态 更新时间:2024-10-19 02:23:10
本文介绍了是否可以在dict键中使用破折号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我对剧本有疑问,想知道问题是否在于我使用的字典中的某些键名中带有破折号.无论是否允许,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] => { "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] => { "block_storage_route[0].destination": "10.201.142.0/24" } TASK [debug] ************************************************************************************************************************ ok: [one.example] => { "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键中使用破折号?

本文发布于:2023-08-02 11:36:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1277479.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:破折号   dict

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!