Access to nested variables in unavailable variables

Here is my group_vars / all file:

app_env: staging staging: app_a: db_host: localhost app_b: db_host: localhost production: app_a: db_host: app_a-db.example.net app_b: db_host: app_b-db.example.com 

If the app_env environment needs to be production, I overwrite it with inventory variables. Thus, all deployments are performed if you do not do them explicitly.

So, when I want to print a variable in a playbook, I can do

 --- - debug: var={{app_env}}.app_a.db_host 

It works!

But how can I access the variable in another module, i.e. lineinfile?

Some examples that did not work:

 - lineinfile: dest=/etc/profile line='export APP_A_DB_HOST="{{ app_env.app_a.db_host }}"' - lineinfile: dest=/etc/profile line='export APP_A_DB_HOST="{{ app_env[app_a][db_host] }}"' - lineinfile: dest=/etc/profile line='export APP_A_DB_HOST="{{ {{app_env}}.app_a.db_host }}"' 

Working solutions will use the set_fact module (double lines of code, not very smart) or including various variable files, depending on app_env.

But I really would like to know if there is a record for accessing nested variable variables;)

+7
ansible
source share
1 answer

You would simplify your life if your “dictate of the environment” were not fundamentally, for example:

 app_env: staging app_environments: staging: app_a: db_host: localhost app_b: db_host: localhost production: app_a: db_host: app_a-db.example.net app_b: db_host: app_b-db.example.com 

Then you can use {{app_environments[app_env].app_a.db_host}} or {{app_environments[app_env]['app_a']['db_host']}} everywhere (Jinja templates, tasks).

Beware too much of “shyness,” though!

+14
source share

All Articles