Nested Jinja2 dictionary valuable is disappearing

Viewed 21

I'm using ansible and jinja2, and need to access a variable.

I have a data structure structure, and executing in a playbook:

  - name: debug_1
    debug:
      msg: "{{ vars['structure'] }}"

Yields these results:

ok: [debug-test] => {
    "msg": {
        "Covo": [
            {
                "enabled": true
            }
        ]
    }
}

Furthermore, running

  - name: debug_1
    debug:
      msg: "{{ vars['structure']['covo'] }}"

gives the expected result:

ok: [debug-test] => {
    "msg": [
        {
            "enabled": true
        }
    ]
}

However, attempting to access the enabled variable with:

  - name: debug_1
    debug:
      msg: "{{ vars['structure']['covo']['enabled'] }}"

Will throw an error:

fatal: [debug-test]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'list object' has no attribute 'enabled'\n\nThe error appears to be in '/task/main.yml': line 16, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n    when: vars['structure']['covo']['enabled']|default(False) == True\n  - name: debug_1\n    ^ here\n"}

How can I access this variable?

1 Answers

covo is an array, so you have to declare the index:

  - name: debug_1
    debug:
      msg: "{{ vars['structure']['covo'][0]['enabled'] }}"
Related