ansible 中的 dict 键中是否允许破折号? [英] Are dashes allowed in dict keys in ansible?

查看:30
本文介绍了ansible 中的 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.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?

推荐答案

问:"Ansible 中的字典键中是否允许使用破折号?"

Q: "Are dashes allowed in dictionary keys in Ansible?"

答:是的.他们是.实际上,YAML 中对密钥没有任何限制.引用自 Mapping(又名 Python 字典)

A: Yes. They are. In fact, there are no restrictions in YAML on the keys. Quoting from Mapping (aka Python dictionary)

"映射节点的内容是一组无序的键:值节点对,限制是每个键都是唯一的.YAML 对节点没有进一步的限制.特别是,键可以是任意节点,......

使用括号表示法 当键的名称不符合 Ansible 创建有效的变量名

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

这篇关于ansible 中的 dict 键中是否允许破折号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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