Reputation: 33
I am trying to figure out a complex variable structure with jinja2 template in Ansible. I have tried different solutions with dictsort and "if" loop inside "for" loop, but I do not see any progress. Any help would be appreciated.
I am trying to print the virtual_ro_id
based on the ansible_hostname
. And hostnames are server1.dc1.com & server2.dc1.com, same for dc2 . The var file is given below.
datacenters:
dc1:
server1:
- virtual_ro_id: "60"
server2:
- virtual_ro_id: "60"
dc2:
server1:
- virtual_ro_id: "61"
server2:
- virtual_ro_id: "61"
This is what my template syntax looks like:
{% for dc in lookup('dict', datacenters) %}
{% set dc_name=ansible_fqdn.split(.)[1] %}
{% if 'dc' == dc_name %}
ID: {{ dc.ansible_hostname.virtual_ro_id }}
{% endif %}
{% endfor %}
I usually get syntax error or no value gets by the template. Thanks in advance.
Upvotes: 1
Views: 511
Reputation: 68294
Given the inventory
shell> cat hosts
server1.dc1.com
server2.dc1.com
server1.dc2.com
server2.dc2.com
the task
- debug:
var: datacenters[mydomain][myhost][0]['virtual_ro_id']
vars:
myhost: "{{ inventory_hostname.split('.').0 }}"
mydomain: "{{ inventory_hostname.split('.').1 }}"
gives
ok: [server1.dc1.com] => {
"datacenters[mydomain][myhost][0]['virtual_ro_id']": "60"
}
ok: [server2.dc1.com] => {
"datacenters[mydomain][myhost][0]['virtual_ro_id']": "60"
}
ok: [server1.dc2.com] => {
"datacenters[mydomain][myhost][0]['virtual_ro_id']": "61"
}
ok: [server2.dc2.com] => {
"datacenters[mydomain][myhost][0]['virtual_ro_id']": "61"
}
Is this probably what you're looking for?
Upvotes: 1