Issue
So I have a provision file with content as follow:
[dev-hosts]
dev-host-1
dev-host-2
dev-host-3
[tst-hosts]
tst-host-1
tst-host-2
tst-host-3
==========
In jenkins I choose an environment (dev, tst) and I need a playbook to get access to a specific item from the groups. I tried an expression as follows:
{{ groups[\"{{ env }}-hosts\"][0] }}
<< this gives me unexpected char u'\\' error and fails the job
{{ groups["{{ env }}-hosts"][0] }}
<< this on the other hand results in 'dict object' has no attribute '{{ env }}-hosts'"}
I went through ansible documentation but found no answer. How can I end up with 'dev-host-1' or any other item from the groups having the {{ env }} variable provided in Jenkins.
Solution
From the documentation:
Another rule is ‘moustaches don’t stack’. We often see this:
{{ somevar_{{other_var}} }}
The above DOES NOT WORK as you expect, if you need to use a dynamic variable use the following as appropriate:
{{ hostvars[inventory_hostname]['somevar_' + other_var] }}
If you want to have a variable concatenated with a string inside a moustaches block, use the Jinja operator designed for this: ~
Mind that the +
sign would also work but migh have side effect, as explained in Jinja documentation:
+
Adds two objects together. Usually the objects are numbers, but if both are strings or lists, you can concatenate them this way. This, however, is not the preferred way to concatenate strings! For string concatenation, have a look-see at the~
operator.{{ 1 + 1 }}
is2
.
Source: https://jinja.palletsprojects.com/en/2.11.x/templates/#math
For example:
"{{ groups[env ~ '-hosts'][0] }}"
Answered By - β.εηοιτ.βε
Answer Checked By - Mildred Charles (JavaFixing Admin)