Are dashes allowed in dict keys in ansible?

笑着哭i 提交于 2021-01-28 07:10:30

问题


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.

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.

The playbook:

- 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

Output:

...
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!"
}

As you can see I get a "VARIABLE IS NOT DEFINED" error. That even though the key "table-id" is present... Why?


回答1:


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

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

"The content of a mapping node is an unordered set of key: value node pairs, with the restriction that each of the keys is unique. YAML places no further restrictions on the nodes. In particular, keys may be arbitrary nodes, ..."

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


来源:https://stackoverflow.com/questions/64982308/are-dashes-allowed-in-dict-keys-in-ansible

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!