How to use a variable within a variable

25 views
Skip to first unread message

Joe Levis

unread,
Jan 28, 2016, 2:16:46 PM1/28/16
to Ansible Project

I have a use case where I need to use a variable within a variable. I'm sure it's doable, but I'm new to Ansible syntax and tried different ways with no success.


Here's the scenario:

1) Playbook uses variable {{ redis_password.qa }} defined in /vars/main.yml:

---

redis_password:

  qa: qa123

  production: prod123


2) We're also passing a variable {{ app_env }} on the command line when running the Playbook:
--extra-vars "app_env=qa"

3) Now, I need to use the variable passed on command line to get the variable from /vars/main.yml:
{{ redis_password.{{ app_env }} }}

Any way to do this?

Josh Smift

unread,
Jan 28, 2016, 2:22:38 PM1/28/16
to ansible...@googlegroups.com
JL> 3) Now, I need to use the variable passed on command line to get the
JL> variable from /vars/main.yml:
JL> {{ redis_password.{{ app_env }} }}

Yep, just the syntax is wrong. Two things:

(1) The {{ and }} marks just say "start parsing Jinja", so you don't ever
need to nest them.

(2) The dotted notation doesn't let you specify what's a literal and
what's a variable. (I think this is confusing, so I personally avoid
it, even though it does have the advantage of being pleasantly more
concise than brackets and quote marks.)

Try

{{ redis_password[app_env] }}

and see if that works. (If you wanted the literal string "app_env", you'd do

{{ redis_password['app_env'] }}

instead.)

-Josh (j...@care.com)



This email is intended for the person(s) to whom it is addressed and may contain information that is PRIVILEGED or CONFIDENTIAL. Any unauthorized use, distribution, copying, or disclosure by any person other than the addressee(s) is strictly prohibited. If you have received this email in error, please notify the sender immediately by return email and delete the message and any attachments from your system.

Joe Levis

unread,
Jan 28, 2016, 2:30:02 PM1/28/16
to Ansible Project, j...@care.com
SUCCESS!

Wow, that was it. Thanks man. I had tried {{ redis_password.[app_env] }} - so close!

And thank you for clarifying the use of jinja.

-Joe
Reply all
Reply to author
Forward
0 new messages