How to access variable name which include a hyphen in Ansible

Viewed 1278

I have a simple vlan config file which I like to have the keys to match with JunOS syntax (this way I can pass them as aggrogate if I need to), so I'm using the vlan-id key like this example variable file.

# vlans.yaml
vlans:
    - name: general
      description: "General"
      vlan-id: 100
    - name: hotline
      description: "Accounting"
      vlan-id: 110

but i can't access the vlan-id key because of the hyphen

    - debug:
        msg: "{{ item.vlan-id }}"
      loop: "{{ vlans }}"
      tags: debug

"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'vlan'

if I output the item directly I can see the key

    - debug:
        msg: "{{ item }}"
      loop: "{{ vlans }}
ok: [SW02] => (item={'name': 'external', 'description': 'External', 'vlan-id': 209}) => {
    "msg": {
        "description": "External",
        "name": "external",
        "vlan-id": 209
    }
}
ok: [SW01] => (item={'name': 'external', 'description': 'External', 'vlan-id': 209}) => {
    "msg": {
        "description": "External",
        "name": "external",
        "vlan-id": 209
    }
}

Any ideas how to solve this?

1 Answers

Put the attributes into the brackets '[]' aka array notation. For example

        msg: "{{ item['vlan-id'] }}"

Quoting from Ansible allows dot notation and array notation for variables. Which notation should I use?

If your variable contains dots (.), colons (:), or dashes (-), if a key begins and ends with two underscores, or if a key uses any of the known public attributes, it is safer to use the array notation.


Q: "This is not a variable, it's the key."

A: Right. The only restriction is the keys are unique. Quoting from YAML 1.2

Mapping. 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, the same node may be used as the value of several key: value pairs, and a mapping could even contain itself as a key or a value (directly or indirectly).

Related