4

在 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
                }
            }
        ]
    }
4

2 回答 2

0

如果你看看ssl_cert_check你有,你会注意到布尔键exists存储在列表stat下的字典results中,所以实际上你应该迭代模板内列表中的项目。

如果您发布的是一致的示例,您可以使用以下方法引用列表中的第一项:

{% if ssl_cert_check.results[0].stat.exists %}

但是,ssl_cert_check在您的情况下创建的方式很可能意味着:

  • 你的代码中有某种循环
  • sitename不是标量值,而是列表本身

如果循环运行了更多次,或者您有多个项目 on sitename,您的结果可能会不一致。

您应该解决根本原因而不是results[0]解决方法。

于 2017-01-09T22:38:48.687 回答
0

请注意:跳过的任务仍将注册变量:

- name: Check if certificate file exists
  stat: path=/etc/nginx/ssl/{{ sitename }}.pem
  register: ssl_cert_check

- name: Check if certificate file exists
  stat: path=/etc/nginx/ssl/{{ sitename }}.pem
  register: ssl_cert_check
  when: nonexistent is defined

在这种情况下,寄存器将具有以下值:

"ssl_cert_check": {
    "changed": false,
    "skip_reason": "Conditional result was False",
    "skipped": true
}

最可能最好为每个寄存器使用唯一的名称?

于 2018-02-25T15:44:54.663 回答