Home > other >  Jinja2 ansible host groups
Jinja2 ansible host groups

Time:01-27

I try to build elasticsearch cluster with ansible and I have a problem with jinja2.

How can I set in jinja2 IP addresses of other hosts?

I have in my inventory.ini:

[elasticsearch]
192.168.0.1
192.168.0.2
192.168.0.3

and I want in jinja2 template to pass two addresses 192.168.0.2,192.168.0.3 when there is more hosts than 1, to look something like that:

- discovery.seeds_hosts=192.168.0.2,192.168.0.3

but when is one host in inventory.ini

it should look like this:

- discovery.seeds_hosts=192.168.0.1

I tried with something like this(hostnames):

{% for host in groups['elasticsearch'] %}{% if host == ansible_host %}{% else %}{%if loop.index0 > 0 %}{% endif %}elasticsearch-{{ loop.index }}{% if not loop.last %},{% endif %}{% endif %}{% endfor %} 

and it works only for more than 1 host in elasticsearch group. If in the inventory.ini is only one host, the variable discovery.seeds_hosts will be empty.

Ansible version:

ansible [core 2.14.1]
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/ansible/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/lib/python3.10/site-packages/ansible
  ansible collection location = /home/ansible/.ansible/collections:/usr/share/ansible/collections
  executable location = /usr/local/bin/ansible
  python version = 3.10.9 (main, Dec  8 2022, 01:46:27) [GCC 10.2.1 20210110] (/usr/local/bin/python)
  jinja version = 3.1.2
  libyaml = True

CodePudding user response:

You could use a conditional that checks the number of hosts:

{% if groups.elasticsearch|length > 1 %}
- discovery.seeds_hosts={{ groups.elasticsearch[1:]|join(',') }}
{% else %}
- discovery.seeds_hosts={{ groups.elasticsearch.0 }}
{% endif %}

I've tested this locally, and with multiple hosts in the inventory:

[elasticsearch]
192.168.0.1
192.168.0.2
192.168.0.3

This produces:

- discovery.seeds_hosts=192.168.0.2,192.168.0.3

With a single host in the inventory:

[elasticsearch]
192.168.0.1

This produces:

- discovery.seeds_hosts=192.168.0.1
  • Related