| Forum

How to use dynamic variable names in Ansible?

I have a couple of variables like site1_app, site2_app, site3_app. This is basically variable names in the pattern <siteid>_app.
I tried accessing the variable as

{{ {{ siteId }}_app }}

But this seems to be not working. Is there something wrong with this method?

As per the Ansible documentation, moustaches don’t stack. i.e. {{ {{ siteId }}_app }} WONT work.

Instead you can use

"{{ vars[siteId + '_app']}}"


- name: set fact
   app_name: "{{ vars[siteId + '_app']}}"