在 Ansible 任务中,如何注册一个变量,以便我可以将它用作模板中的检查语句。任务是:
- name: Check if certificate file exists
stat: path=/etc/nginx/ssl/{{ sitename }}.pem
register: ssl_cert_check
- name: Create vhost from template
template: "src={{ vhost_conf }} dest=/etc/nginx/conf/vhost.conf"
在 vhost 的模板中listen 80始终可用,我只想listen 443在证书可用时添加块:
server {
listen 80;
........
}
{% if ssl_cert_check == True %} # This doesn't issue error but doesn't work either
server {
listen 443;
..............
}
{% endif %}
当我运行上述情况时,第二个服务器块没有被执行,这意味着只有服务器监听 80 被打印在 vhost 配置中。
但是,如果我删除 True forif语句并添加stat.exists到模板中,则会出现错误:
# This issues error
{% if ssl_cert_check.stat.exists %}
server {
listen 443;
..............
}
{% endif %}
错误是:
"msg": "AnsibleUndefinedVariable: 'dict object' has no attribute 'stat'即使我在注册变量之前使用了 stat 模块。
有没有其他方法可以传递 Ansible 任务中定义的变量并在 Jinja2 模板中使用它?
- debug: var=ssl_cert_check之前的任务显示的值Create vhost from template是:
"ssl_cert_check": {
"changed": false,
"msg": "All items completed",
"results": [
{
"_ansible_item_result": true,
"_ansible_no_log": false,
"changed": false,
"invocation": {
"module_args": {
"checksum_algorithm": "sha1",
"follow": false,
"get_checksum": true,
"get_md5": true,
"mime": false,
"path": "/etc/nginx/ssl/abc.pem"
},
"module_name": "stat"
},
"item": {
........
},
"stat": {
"exists": false
}
}
]
}