FreeKB - Ansible lookup vars
Ansible - lookup vars

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 }}"

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |