Bootstrap FreeKB - Ansible - Create variables on Ansible controller using lookup vars
Ansible - Create variables on Ansible controller using lookup vars

Updated:   |  Ansible articles

lookup vars (as the name implies) is used for your Ansible control node (that's your Ansible server) to lookup and return the value of a variable. Sometimes, variables are created on your managed nodes (the target systems). For example, let's say you have the following playbook. This would create the "ipv4" variable on each target node and then debug is used to display the "ipv4" value. 

---
- hosts: all
  tasks:
  - set_fact:
      ipv4: ansible_default_ipv4.address

  - debug:
      var: ipv4
...

 

lookup vars can be used for your Ansible controller to evaluate a variable created on a managed node. 

To use the vars lookup 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.

---
- hosts: all
  tasks:
  - set_fact:
      ipv4: ansible_default_ipv4.address

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

 

Or, you can use the full path to the vars lookup plugin - ansible.builtin.vars.

---
- hosts: all
  vars:
    foo: bar
  tasks:
  - debug:
      msg: "{{ lookup('ansible.builtin.vars', 'foo') }}"
...

 

Something like this should be returned.

TASK [debug]
ok: [localhost] => {
    "msg": "bar"
}

 

One thing that is kind of unique and powerful about the lookup plugin is being able to search with multiple "parts" of a variable name.

---
- hosts: all
  vars:
    password_dev: devpw
    password_prod: prodpw
  tasks:
  - debug:
      msg: "{{ lookup('vars', 'password_' + 'dev' ) }}"
...

 

Or like this.

---
- hosts: all
  vars:
    password_dev: devpw
    password_prod: prodpw
    env: dev
  tasks:
  - debug:
      msg: "{{ lookup('vars', 'password_' + env ) }}"
...

 

Which should return the following.

TASK [debug]
ok: [localhost] => {
    "msg": "devpw"
}



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 0a4625 in the box below so that we can be sure you are a human.