reference variables from inventory file in a jinja2 hostvars loop

Hi all,

Can any one help me with the below, im trying to reference variables from my inventory file in a jinja2 hostvars loop. Ive copied the host file and jinja template below.

Template File

In my Jinja 2 template i have the following loop

{% for host in groups[‘redishosts’:‘haproxyhosts’] %}
sentinel known-sentinel mymaster {{ hostvars[host][‘ansible_eth0’][‘ipv4’][‘address’] }} 26379 {{ hostvars[host][‘sentinel_id’].value }}
{% endfor %}

The idea being that i want to pull the variables ie the systems ip and the sentinel_id varaible from the host facts and inventory file variable, listed below

Inventory File

[redishosts]
192.168.0.1 ansible_ssh_private_key_file=~/.ssh/id_rsa redis_role=master sentinel_id=‘1234567’
192.168.0.1 ansible_ssh_private_key_file=~/.ssh/id_rsa redis_role=slave sentinel_id=‘7654321’

Thanks for any help

The problem isn’t with how you are accessing it really, it’s more of a problem with your groups in your for loop. That is invalid.

Instead of:

groups[‘redishosts’:‘haproxyhosts’]

You will likely want:

lookup(‘inventory_hostnames’, ‘redishosts:haproxyhosts’)

Additionally, you don’t need the .value on the end.

So putting it together:

{% for host in lookup(‘inventory_hostnames’, ‘redishosts:haproxyhosts’) %}
sentinel known-sentinel mymaster {{ hostvars[host][‘ansible_eth0’][‘ipv4’][‘address’] }} 26379 {{ hostvars[host][‘sentinel_id’].value }}
{% endfor %}

Alternatively, you may also be able to do:

{% for host in groups[‘redishosts’] + groups[‘haproxyhosts’] %}

or
{% for host in groups['redishosts']|union(groups['haproxyhosts'] %}

Thanks both worked but I have a new error. Ansible undefined variable. Then it prints out the sentinel id. So it does see the content of the sentinel_id host file variable .