Change variable in Ansible template based on group

To avoid error with non existing group you should check first if the group exists:

{% if 'es-masters' in group_names and ansible_fqdn in groups['es-masters'] %}
node_master=true
{% else %}
node_master=false
{% endif %}

If your inventory does not identify hosts with ansible_fqdn, ansible_hostname, etc., you can also use group_names to check if the current host has "es-masters" as one of its groups.

{% if 'es-masters' in group_names %}
node_master=true
{% else %}
node_master=false
{% endif %}

See https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#accessing-information-about-other-hosts-with-magic-variables


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.

{% 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

# role_name/templates/template.j2
node_master={{ role_name_node_master | default(true) }}

Than override in group_vars

# group_vars/es-masters.yml
role_name_node_master: false