How to specify "if else" statements in Ansible Jinja2 (.j2) templates?

18,452

Solution 1

How to use if statements in j2 templates?

You should read the docs. Here is a simple example:

{% if my_var == 1 %}
some text here with an actual variable: {{ my_other_var }}
{% else %}
some other text here with nothing
{% endif %}

Solution 2

You are mixing concepts here.

  1. Ansible can ship a file to a remote server.
  2. At the moment Ansible ships the file to the server, the Jinja template will be interpreted

Here, you are testing the existence of a directory, but do you really want this to be tested at the moment Ansible ships the bash script to the remote server? Or do you rather want your bash script to test for the existence of the said folder on each run?

  • If the answer is:

    at the time Ansible ships the bash script

    then using a Jinja template is a good fit, but I suspect this is not the answer you want.

    first_time=true
    {% if '/backup/db' is directory %}
      first_time=false
      sudo -u tomcat ln -s /backup/app /opt/tomcat/latest/webapps/msales
      sudo -u tomcat ln -s /backup/store/logs /opt/tomcat/latest/logs
      # ...
    {% endif %}
    

    So mind that, in this case, if the folder does not exists at the moment the script is shipped to the remote host, the resulting bash would look like:

    first_time=true
    
  • If the answer is:

    each time we execute the script

    then your condition should be a bash condition in the script itself.

    DIR="/backup/db"
    first_time=true
    if [ -d "$DIR" ]; then
      first_time=false
      sudo -u tomcat ln -s /backup/app /opt/tomcat/latest/webapps/msales
      sudo -u tomcat ln -s /backup/store/logs /opt/tomcat/latest/logs
      # ...
    fi
    
Share:
18,452
Dusty
Author by

Dusty

Updated on June 16, 2022

Comments

  • Dusty
    Dusty almost 2 years

    I'm running an if statement in a bash script. And I need to deploy the bash script in a different server. Below is my if else statement.

    DIR="/backup/db"
    first_time=true
    {% if [ -d "$DIR" ]; then %}
      first_time=false
      sudo -u tomcat ln -s /backup/app /opt/tomcat/latest/webapps/msales
      sudo -u tomcat ln -s /backup/store/logs /opt/tomcat/latest/logs
      .....etc
    {% fi %}
    

    I'm using Ansible to deploy to this script.sh.j2 to the other server. But it says

    ""msg": "AnsibleError: template error while templating string: expected token ',', got 'string'."

    How to use if statements in j2 templates?