Ansible Jinja2 string comparison

ansible, ansible-template, jinja2

Solution

You don't need quotes and braces to refer to variables inside expressions. The correct syntax is:

{% if 'abc' == env %}
serverURL: '{{ server_abc }}'
{% elif 'def' == env %}
serverURL: '{{ server_def }}'
{% elif 'xyz' == env %}
serverURL: '{{ server_xyz }}'
{% else %}
ServerURL: 'server URL not found'
{% endif %}

Otherwise you compare two strings, for example `abc` and `{{env}}` and you always get a negative result.

Problem

I am getting value of variable "env" in Jinja2 template file using a variable defined in group_vars like: ``` env: "{{ defined_variable.split('-')[0] }}" ``` `env` possible three values could be `abc`, `def`, `xyz`. On the basis of this value I want to use server URL, whose possible values I have defined inside `defaults/main.yml` as: ``` server_abc: https://xxxx.xxx.com server_def: https://xxxxx.xxx.com server_xyz: https://xxxx.xxx.com ``` In Jinja2 template, I am trying to do: ``` {% if 'abc' == "{{env}}" %} serverURL: '{{ server_abc }}' {% elif 'def' == "{{env}}" %} serverURL: '{{ server_def}}' {% elif 'xyz' == "{{env}}" %} serverURL: '{{ server_xyz }}' {% else %} ServerURL: 'server Url not found' {% endif %} ``` However it is always ending up defining `ServerURL = "server URL not found"` even if `env` comes with value of `abc`, `def` or `xyz`. If I try to replace env in Jinja2 template (hardcoded) like below condition does satisfy to true: ``` {% if 'abc' == "abc" %} serverURL: '{{ server_abc }}' ``` So that implies me syntax is true but the value of `"{{env}}"` at run time is not evaluated. Any suggestion what can I do to solve this?

Original source