I'm trying to generate a file using a template with Ansible and Jinja2 but I can't seem to get a variable to be recognized.
I have numerous datacenters (dc) and this is declared as "dc" in my hosts_vars file for the host I am running this playbook against. I can call "dc" within the template and it works. My problem lies when I need to call a group of that "dc",
i.e. my datacenter is 'tucson' and I have a group within 'tucson' that is called 'tucson-linux'. I need to be able to dynamically get the list of hosts from 'tucson-linux'. I can do this statically with the following code, In this case, I am grabbing 'gui_addr' from each host in that group.
My template:
{
"cluster": {
"name": "{{ dc|upper }}-Cluster",
"config": {
"ip-address": [ {% for host in groups['tucson-linux'] %}"{{ hostvars[host].gui_addr + '",' }}{% endfor %} ]
}
}
I've tried different variations of substituting 'tucson' with the "dc" var but no luck, I have read that you can't nest jinja expressions which appears to be what I am trying to do
{
"cluster": {
"name": "{{ dc|upper }}-Cluster",
"config": {
"ip-address": [ {% for host in groups['{{dc}}-linux'] %}"{{ hostvars[host].gui_addr + '",' }}{% endfor %} ]
}
}
The error,
fatal: [tucson-server-01]: FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'dict object' has no attribute '{{dc}}-linux'"}
Can someone help me understand why this doesn't work?
Once you've gotten into Jinja template land, you don't need to use more curly braces; you can use the Jinja template language (which bears a strong resemblance to Python in many cases).
In particular, where you write:
{% for host in groups['{{dc}}-linux'] %}
If you were in, say, Python, you'd concatenate the variable dc
and the string -linux
. Jinja has a specific string concatenation operator and I think this should work
{% for host in groups[dc ~ '-linux'] %}