Ansible Jinja2 string comparison
Asked Answered
H

1

19

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?

Hid answered 17/10, 2016 at 12:39 Comment(0)
D
53

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.

Domash answered 17/10, 2016 at 13:3 Comment(3)
Even after removing braces from the env, it is ending on server URL not foundHid
if I use any other variable from group vars, the expression does evaluate to be true in match condition, however the env variable is getting populated in same jinja teamplate file by expression:- env: "{{ defined_variable.split('-')[0] }}"Hid
I was able to achieve purpose by having my conditional statement as if % if 'abc' == defined_variable.split('-')[0] %} serverURL: '{{ server_abc }}'Hid

© 2022 - 2024 — McMap. All rights reserved.