Luke
Luke

Reputation: 59

Jinja2 Template: Nested for and if condition problem

I have to write a shell script based on a series of "if and for" conditions (nested) written in jinja2 (to be used in ansible).

The problem is that an error of "undefined variable: webroot" is returned and I don't understand why.

This is the jinja2 code (under templates folder):

#!/bin/bash
certbot certonly -n --webroot
{% for hosting in hostings %}
{%   if inventory_hostname in hosting.servers %}
   -w {{ hosting.webroot }}
{%     for domain in hosting.domains %}
         -d {{ domain }}
{%     endfor %}
{%   endif %}
{% endfor %}
#-m {{ hosting.letsencrypt_email }} --agree-tos
-m [email protected] --agree-tos

Variable "webroot" exist in a vars/main.yml and it's the same of the "servers" variable that is correctly scoped.

vars/main.yml file:

hostings:
 - name: 'Wottts'
   servers:
     - 'w2.test.it'
     - 'w.test.it'
     - 'w.yat.it'
   template: 'template.conf.j2'
   webroot: '/var/www/test/html'
   domains:
     - 'pippus.invalid'
     - 'www.pippus.invalid'

The error is fatal: [host.name.it]: FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'webroot' is undefined"}

Thanks for any help/suggestion.

Upvotes: 0

Views: 247

Answers (1)

Luke
Luke

Reputation: 59

I solved it by myself!

The problem was on the penultimate line:

...
{% endfor %}
#-m {{ hosting.letsencrypt_email }} --agree-tos
-m [email protected] --agree-tos

Seems that the line that started with the "#" character was the problem, removing it the variables are correctly recognized.

Upvotes: 0

Related Questions