Ansible Template模块推送文件时,当遇到含有特殊字符的配置文件,如:”;” “#”等,如果不加处理,在执行Ansible-playbooks时会报错,因为这些模块不能被正确解析,如下图所示:
<!--more-->
image

解决办法一

使用jinja2的Comments,注释掉那些特殊字符,语法:“{# … #}”,参考:http://jinja.pocoo.org/docs/2.9/templates/#comments

sed -i '/^;/s/^;/{#;/g' www.conf.j2
sed -i '/^{#/s/$/#}/g' www.conf.j2

Jinja2分隔符配置如下:

{% ... %} for Statements
` `.``.``.` ` for Expressions
{# ... #} for Comments
# ... ## for Line Statements

参考:
Statements
Expressions to print to the template output
Comments not included in the template output
Line Statements

效果图:
image
image

解决办法二

使用jinja2的Escaping,把这些特殊字符转义,语法:“{% raw %} … {% endraw %}”,参考:http://jinja.pocoo.org/docs/2.9/templates/#escaping

sed -i '/^;/s/^;/{% raw %};/g' www.conf.j2
sed -i '/^{% raw %}/s/$/{% endraw %}
/g' www.conf.j2

Jinja2转义符:

#被raw包含起来的部分被转义,不会被解析
{% raw %}
;aaa
#bbb
{% endraw %}

效果图:
image
image