18

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?

techraf
  • 64,883
  • 27
  • 193
  • 198
Ruchir Bharadwaj
  • 1,132
  • 4
  • 15
  • 31

1 Answers1

52

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.

techraf
  • 64,883
  • 27
  • 193
  • 198
  • Even after removing braces from the env, it is ending on server URL not found – Ruchir Bharadwaj Oct 17 '16 at 15:12
  • 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] }}" – Ruchir Bharadwaj Oct 17 '16 at 15:34
  • I was able to achieve purpose by having my conditional statement as if % if 'abc' == defined_variable.split('-')[0] %} serverURL: '{{ server_abc }}' – Ruchir Bharadwaj Oct 17 '16 at 15:40