Ansible: build variable name from other variable and string


Recently, I ran into the following problem: “How to get the value of an Ansible variable, where its name is constructed by concatenating other variables and/or strings”.

I found the solution in the documentation pretty and I’m sharing it because it took a little while longer to make it work than other issues I have faced before in my plays.

Example:

The following variables have been defined somewhere:

    best_animal: 'Dog'
    best_person: 'Michael'
    favourite: 'animal'

And, let’s assume that you would like to access the best_* variables on the fly, by just editing the favourite variable’s value, perhaps when running the Ansible role via the command line, or selecting its value in a menu in Jenkins, etc.

  

What you would have to do, is to concatenate the two ansible variables names, like so:

- debug:
    msg: “{{ vars['best_'+favourite] }}”

This would give you this output:

ok: [localhost] => {}

MSG:

“Dog”

Similarly, if we run:

ansible-playbook example_playbook.yml -e favourite=person

we will get:

ok: [localhost] => {}

MSG:

“Michael”

This works with lists, of course. So, in case your next Ansible role is getting complex, you can try this little trick.

I hope the example is easy to understand 🙂

If this helped you, please feel free to give me a tip! https://ko-fi.com/kostavro