我一直在研究一种手动呈现jinja2模板的方法,这是我对ansible所需的。
这给我带来了python呈现功能,但遗憾的是,我的python几乎不存在。
然而,使用google搜索找到的示例脚本看起来相当简单(乍一看)。
我的模板包括一个for循环,这就是我遇到一些困难的地方。
jinja2模板:
{% if extendedKeyUsage is defined and extendedKeyUsage %}
subjectAltName = {% for SAN_IP in TLS_IP_SANS %}IP:{{ SAN_IP }}, {% endfor %}{% for SAN_DNS in TLS_DNS_SANS %}DNS:{{ SAN_DNS }}, {% endfor %}IP:127.0.0.1
extendedKeyUsage = clientAuth,serverAuth
{% endif %}如您所见,我尝试从模板生成一个openssl扩展用例文件。(但这不是重点)
脚本:
#!/usr/bin/python
#
# stolen from https://stackoverflow.com/questions/42090084/how-can-i-unit-test-jinja2-template-logic
# but real working info found here: http://matthiaseisen.com/pp/patterns/p0198/
#
import os
import jinja2
def render(tpl_path, context):
path, filename = os.path.split(tpl_path)
return jinja2.Environment(
loader=jinja2.FileSystemLoader(path or './')
).get_template(filename).render(context)
context = { # your variables to pass to template
'extendedKeyUsage': 'true',
'TLS_IP_SANS': '10.1.17.101',
# 'TLS_DNS_SANS': 'test.crapco.labs'
'TLS_DNS_SANS': 'test.crapco.labs, www.crapco.labs, a.crapco.lab'
}
filename = '/root/20160921/roles/ansible-role-CA/templates/crtExtendedUse.j2'
rendered = render(filename, context)
print "this is the rendered template %s." % rendered唉,它似乎没有在for -循环的上下文中使用逗号分隔的值,而是接受每个字符。
结果:
[user@kvm-centos7-ansible ansible-role-CA]# ./render_jinja2.py
this is the rendered template
subjectAltName = IP:1, IP:0, IP:., IP:1, IP:., IP:1, IP:7, IP:., IP:1, IP:0, IP:1, DNS:t, DNS:e, DNS:s, DNS:t, DNS:., DNS:c, DNS:r, DNS:a, DNS:p, DNS:c, DNS:o, DNS:., DNS:l, DNS:a, DNS:b, DNS:s, DNS:,, DNS: , DNS:w, DNS:w, DNS:w, DNS:., DNS:c, DNS:r, DNS:a, DNS:p, DNS:c, DNS:o, DNS:., DNS:l, DNS:a, DNS:b, DNS:s, DNS:,, DNS: , DNS:a, DNS:., DNS:c, DNS:r, DNS:a, DNS:p, DNS:c, DNS:o, DNS:., DNS:l, DNS:a, DNS:b, IP:127.0.0.1
extendedKeyUsage = clientAuth,serverAuth
.我怎么才能得到完整的字符串?
发布于 2017-07-24 14:19:20
答案是我对什么是要循环的列表/数组有错误的理解。对上下文使用以下内容可以很好地完成的工作:
context = { # your variables to pass to template
'extendedKeyUsage': 'true',
'TLS_IP_SANS': ['10.1.17.101'],
'TLS_DNS_SANS': ['test.crapco.labs', 'www.crapco.labs', 'a.crapco.lab']
}现在,输出与预期的一样:
this is the rendered template
subjectAltName = IP:10.1.17.101, DNS:test.crapco.labs, DNS:www.crapco.labs, DNS:a.crapco.lab, IP:127.0.0.1
extendedKeyUsage = clientAuth,serverAuth
.https://stackoverflow.com/questions/45282687
复制相似问题