在 Ansible Jinja 模板中使用命令
Using commands in Ansible Jinja template
我正在尝试创建一个 jinja2 模板,它将使用条件检查服务器位置,然后将更改相应地推送到服务器。
在我下面的模板文件中,我尝试 运行 命令并检查它是否符合预期的位置。
config.j2
{% if `hostname -s|cut -c 1-2` == "ny" -%}
options timeout:1 attempts:2
search us.xyz.com
nameserver 1.1.3.2
nameserver 1.2.3.4
{% elif `hostname -s|cut -c 1-2` == "au" -%}
options timeout:1 attempts:2
search us.xyz.com
nameserver 1.1.3.9
nameserver 1.2.3.8
{% endif %}
其抛出错误为:
"msg": "AnsibleError: template error while templating string: unexpected char u'`'
jinja 模板允许使用系统命令还是根本不允许?任何建议或线索都会有所帮助!
Does the jinja template allows using system commands or not at all?
不,不是。
不仅没有这样的语法,而且模板将在本地计算机上执行,因此您示例中的 hostname
将始终解析为控制计算机的名称。
但是根本没有理由这样做,只需按以下方式使用Ansible:
{% if ansible_hostname[0:2] == "ny" -%}
我正在尝试创建一个 jinja2 模板,它将使用条件检查服务器位置,然后将更改相应地推送到服务器。
在我下面的模板文件中,我尝试 运行 命令并检查它是否符合预期的位置。
config.j2
{% if `hostname -s|cut -c 1-2` == "ny" -%}
options timeout:1 attempts:2
search us.xyz.com
nameserver 1.1.3.2
nameserver 1.2.3.4
{% elif `hostname -s|cut -c 1-2` == "au" -%}
options timeout:1 attempts:2
search us.xyz.com
nameserver 1.1.3.9
nameserver 1.2.3.8
{% endif %}
其抛出错误为:
"msg": "AnsibleError: template error while templating string: unexpected char u'`'
jinja 模板允许使用系统命令还是根本不允许?任何建议或线索都会有所帮助!
Does the jinja template allows using system commands or not at all?
不,不是。
不仅没有这样的语法,而且模板将在本地计算机上执行,因此您示例中的 hostname
将始终解析为控制计算机的名称。
但是根本没有理由这样做,只需按以下方式使用Ansible:
{% if ansible_hostname[0:2] == "ny" -%}