1

I am writing a jinja2 template for an Ansible role. I have this in my role/x/vars/main.yml

switches:
  - hostname: foo
    customer: abc
    abc_secret_key: myP@$$word
    xyz_secret_key: myS3cr3t

In my template, I want to reference the secret key based on the value of customer variable.

I can reference abc_secret_key by using {{ item.abc_secret_key }}. That works, no problem. However I really want to build the variable name dynamically and use the value of the "customer" variable (in the case abc) as part of variable name abc_secret_key.

This does not work.
I get

"msg": "AnsibleUndefinedVariable: 'dict object' has no attribute u'abc'"

but, hopefully it illustrates what I am trying to do

my secret key is {{ item[item.customer]['_secret_key'] }}

I would like it to render like this:

my secret key is myP@$$word

I have tried about 10-15 different renditions but, can not pin down the right syntax.

Kevin C
  • 4,851
  • 8
  • 30
  • 64
pizzaguy39
  • 87
  • 5

1 Answers1

2

As you see the dict key lookup with a literal string key, you can compose a dynamic string to serve as the dict key:

- debug:
    msg: my secret key is {{ item[ item.customer ~ '_secret_key'] }}

Where the ~ is jinja2 syntax for string concatenation where either side is first coerced to a string, and then concatenated. You are welcome to use +, too, if you are certain that both sides are already strings (as is likely the case here, base on your cited example):

- debug:
    msg: my secret key is {{ item[ item.customer + '_secret_key'] }}
mdaniel
  • 31,240
  • 5
  • 55
  • 58