Question:
I’ve got an Ansible inventory file a bit like this:
1 2 3 4 5 6 7 8 9 10 11 |
[es-masters] host1.my-network.com [es-slaves] host2.my-network.com host3.my-network.com [es:children] es-masters es-slaves |
I also have a Jinja2 template file that needs a certain value set to “true” if a host belongs to the “es-masters” group.
I’m sure that there’s a simple way of doing it but after some Googling and reading the documentation, I’ve drawn a blank.
I’m looking for something simple and programmatic like this to go in the Jinja2 template:
1 2 3 4 5 6 |
{% if hostvars[host][group] == "es-masters" %} node_master=true {% else %} node_master=false {% endif %} |
Any ideas?
Answer:
You do it the other way around.
You check if the identifier (hostname or IP or whatever is in your inventory) is in the defined group. Not if the group is in the hostvars.
1 2 3 4 5 6 |
{% if ansible_fqdn in groups['es-masters'] %} node_master=true {% else %} node_master=false {% endif %} |
But, what you better should do is this:
Provide default in template
1 2 3 |
# role_name/templates/template.j2 node_master={{ role_name_node_master | default(true) }} |
Than override in group_vars
1 2 3 |
# group_vars/es-masters.yml role_name_node_master: false |