2017-07-24 104 views
0

我一直在尋找一種方法來手動渲染jinja2模板,我需要爲ansible。jinja2蟒蛇渲染「for循環」

這給我帶來了python jinja渲染功能,但唉,我的python幾乎不存在。

但是,使用谷歌搜索發現示例腳本看起來很簡單(乍)

我的模板包括一個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循環,它似乎把每一個字符。

結果:

[[email protected] 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 
. 

我怎樣才能得到完整的字符串?

+0

它出現在我的列表的理解是錯誤的。並使用[]正確地解決了這個問題...像:''TLS_DNS_SANS':['test.crapco.labs','www.crapco.labs','a.crapco.lab']' – lievendp

回答

0

答案是我有缺陷的理解什麼是列表/數組循環。 使用背景下制定了罰款:

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 
.