Ansible Jinja2 string comparison

65,356

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.

Share:
65,356
Ruchir Bharadwaj
Author by

Ruchir Bharadwaj

Updated on February 07, 2020

Comments

  • Ruchir Bharadwaj
    Ruchir Bharadwaj about 4 years

    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?

  • Ruchir Bharadwaj
    Ruchir Bharadwaj over 7 years
    Even after removing braces from the env, it is ending on server URL not found
  • Ruchir Bharadwaj
    Ruchir Bharadwaj over 7 years
    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
    Ruchir Bharadwaj over 7 years
    I was able to achieve purpose by having my conditional statement as if % if 'abc' == defined_variable.split('-')[0] %} serverURL: '{{ server_abc }}'