Question:
Here is my problem I need to use one variable ‘target_host’ and then append ‘_host’ to it’s value to get another variable name whose value I need.
If you look at my playbook. Task nbr 1,2,3 fetch the value of variable however nbr 4 is not able to do what I expect. Is there any other way to achieve the same in ansible?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
--- - name: "Play to for dynamic groups" hosts: local vars: - target_host: smtp - smtp_host: smtp.max.com tasks: - name: testing debug: msg={{ target_host }} - name: testing debug: msg={{ smtp_host }} - name: testing debug: msg={{ target_host }}_host - name: testing debug: msg={{ {{ target_host }}_host }} Output: TASK: [testing] *************************************************************** ok: [127.0.0.1] => { "msg": "smtp" } TASK: [testing] *************************************************************** ok: [127.0.0.1] => { "msg": "smtp.max.com" } TASK: [testing] *************************************************************** ok: [127.0.0.1] => { "msg": "smtp_host" } TASK: [testing] *************************************************************** ok: [127.0.0.1] => { "msg": "{{{{target_host}}_host}}" } |
Answer:
This (AFAIK) isn’t possible. The primary limitation that stops us doing this (no matter how you spin it), is ‘variable expansion’ in ansible is a single pass process and what you want requires multiple-passes.
Only [seriously hacky] ways I can think of are:
- Create the playbook dynamically from your playbook using
template
and execute it. - I heard that Jinja2 engine does multi-pass evaluation. May be if you put these strings in a template and then use the
lookup('template', ...)
filter. Unfortunately I have no experience with Jinja2 templates so not quite sure if this is even an option.