【问题标题】:Jinja2 Template: Nested for and if condition problemJinja2 模板:嵌套用于和 if 条件问题
【发布时间】:2019-09-25 11:42:05
【问题描述】:

我必须根据用jinja2编写的一系列“if and for”条件(嵌套)编写一个shell脚本(用于ansible)。

问题是返回“undefined variable: webroot”的错误,我不明白为什么。

这是 jinja2 代码(在 templates 文件夹下):

#!/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 info@email.it --agree-tos

变量“webroot”存在于 vars/main.yml 中,它与正确作用域的“servers”变量相同。

vars/main.yml 文件:

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'

错误是 致命的:[host.name.it]: FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'webroot' is undefined"}

感谢任何帮助/建议。

【问题讨论】:

  • 你最好的办法是尝试解析为什么它没有显示你的想法,特别是因为你不认为错误是在服务器变量上,将模板打印到某个地方一个测试,但是将整个宿主变量打印到模板中,以确保它不会拖入您不期望的东西(例如,您可能在某处重复使用变量,因此您不会拉入您的想法你是)。

标签: ansible jinja2


【解决方案1】:

我自己解决了

问题出在倒数第二行:

...
{% endfor %}
#-m {{ hosting.letsencrypt_email }} --agree-tos
-m info@email.it --agree-tos

似乎以“#”字符开头的行是问题所在,删除它,变量被正确识别。

【讨论】:

    猜你喜欢
    • 2016-07-18
    • 2021-09-26
    • 1970-01-01
    • 2017-05-15
    • 2018-09-17
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多