JeremyCanfield
JeremyCanfield

Reputation: 673

Ansible accessing Nested Variables

In foo.yml, the dev.foo variable contains a value of bar.

---
- hosts: all
  vars:
    dev:
      foo: bar

I set the env variable to contain a value of dev on the command line.

ansible-playbook foo.yml --extra-vars "env=dev"

If I attempt to debug env.foo . . .

  tasks:
    - debug:
        msg: "{{ env.foo }}"

The following is returned.

TASK [debug]
fatal: [server1.example.com]: FAILED! => {
    "msg": "The task includes an option with an undefined variable.
            The error was: 'str object' has no attribute 'foo'"
}

I am not sure how to resolve env to dev in jinja2 and then access nested variable dev.foo.

Upvotes: 1

Views: 847

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68189

Indirect addressing is not available in Ansible. You can use vars lookup instead. See ansible-doc -t lookup vars e.g.

  - debug:
      msg: "{{ lookup('vars', env).foo }}"

gives

  msg: bar

Upvotes: 1

Related Questions