Bootstrap FreeKB - Ansible - lookup vars and nested variables
Ansible - lookup vars and nested variables

Updated:   |  Ansible articles

Following are the differet ways that variables can be set in Ansible. This list is in the order of precedence, where the option higher in the list takes precedence over options lower in the list.

The lookup plugin is always executed on the control node (that's your Ansible server), which is to say that the lookup plugin does not do something on your managed nodes (the target systems).

To use the vars plugin, the Python vars.py script must be in your Ansible plugins lookup directory, such as /usr/lib/python2.7/site-packages/ansible/plugins/lookup/vars.py.

Let's say foo.yml contains the following. Notice the vars plugin is being used to create nested variable dev.foo.

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

 

The vars lookup plugin can be used to access the nested variables. In this example, the root key (dev) is accessed.

- debug:
    msg: "{{ lookup('vars', dev) }}"

 

Something like this should be returned.

TASK [debug]
ok: [server1.example.com] => {
    "msg": {
        "dev": {
            "foo": "bar"
        }
    }
}

 

Let's say you want to access the value in the foo key. You would do this.

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

 

Or this.

- debug:
    msg: "{{ lookup('vars', dev)['foo'] }}"

 

Something like this should be returned.

TASK [debug]
ok: [server1.example.com] => {
    "msg": "bar"
}

 

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

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

 

And attempt to print the env.foo nested variable using the debug module . . .

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

 

Something like this will be 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'"
}

 

This is because indirect addressing is not supported. The lookup plugin can be used.

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

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 46e702 in the box below so that we can be sure you are a human.