Use an ansible fact in an if conditional - Jinja template

Viewed 1399

At the moment I have something like the following in my Ansible Jinja Template

{% for key in filebeat.values() %}
{% for x in key.servers %}
{% if x in {{ ansible_hostname }} %}
text-goes-here
{% endif %}
{% endfor %}
{% endfor %}

When executing the ansible playbook, the following error is showing:

AnsibleError: template error while templating string: expected token ':', got '}

It seems that with Jinja, I cannot make use of {{ ansible_hostname }} inside an if statement.

Is there some way that I can still get the value of ansible_hostname inside the if statement to get around this issue? I have tried using lookup and other combinations but no luck so far.

Thanks in advance

1 Answers

You never nest Jinja {{...}} template markers. If you're already inside a template context, you can just refer to variables by name...

{% if x in ansible_hostname %}
text-goes-here
{% endif %}

You're already using exactly the correct syntax in your {% for ... %} loops. You wrote:

{% for key in filebeat.values() %}

Instead of:

{% for key in {{ filebeat.values() }} %}

The {% if ... %} statement is no different.

Related