Are dashes allowed in dict keys in ansible?

Viewed 1289

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 Answers

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