13

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 app_env environment has to be production, I overwrite this via inventory variables. This way, all deployments are staging unless you make them production explicitly.

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

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

This works!

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

Some Examples that didn't work out:

- 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 would be using the set_fact module (double lines of code, not really smart) or including different variable files, depending on app_env.

But I really would like to know if there's a notation to access nested variable variables ;)

U880D
  • 8,601
  • 6
  • 24
  • 40
witsches
  • 227
  • 2
  • 3
  • 7

1 Answers1

24

You would make your life easier with your 'environment dict' not being at the root, like so:

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 should be able to use {{app_environments[app_env].app_a.db_host}} or {{app_environments[app_env]['app_a']['db_host']}} everywhere (Jinja templates, tasks).

Watch out for too much "nestiness" though !

leucos
  • 17,661
  • 1
  • 44
  • 34