Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 239
Dusty Avatar asked Dec 30 '25 22:12

Dusty


1 Answers

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 %}
like image 95
Kevin C Avatar answered Jan 01 '26 13:01

Kevin C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!