Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use value of CLI variable as the name of a host_vars variable?

Is there a way to use the value of one Ansible variable as the name of another variable so I can extract a value from its list?

host_vars:

this:
  does: walk
  says: hi

that:
  does: run
  says: hello

On the CLI when I run the playbook, I add -e="thing=this".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In the playbook, I’ve tried all manner of things to expand the variable thing to its value this, then use this to extract the value of does in the host_vars file.

Using the variable name directly obviously works:

- name: Check what the thing does
  debug:
    msg: "{{ this['does'] }}"

But the following do not:

{{ thing['does'] }}
{{ {{ thing }}['does'] }}

Those, plus several other iterations I’ve tried all either throw an error or print out the literal string.

>Solution :

You need the vars lookup plugin to indirectly address variables. See

shell> ansible-doc -t lookup vars

For example,

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

should give (abridged)

shell> ansible-playbook pb.yml -e "thing=this"
  ...
  msg: walk

Example of a complete playbook for testing

- hosts: localhost

  vars:

    this:
      does: walk
      says: hi
    that:
      does: run
      says: hello

  tasks:

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading