字符串不匹配时的 Ansible 条件

Ansible condition when string not matching

我正在尝试编写一个 Ansible 剧本,它只在 Nginx 不存在且处于当前版本时才编译它。但是它每次都会编译,这是不可取的。

这是我的:

- shell: /usr/local/nginx/sbin/nginx -v 2>&1
  register: nginxVersion
- debug:
  var=nginxVersion

- name: install nginx
  shell: /var/local/ansible/nginx/makenginx.sh
  when: "not nginxVersion == 'nginx version: nginx/1.8.0'"
  become: yes

除了每次编译 Nginx 时都会运行 shell 脚本之外,该脚本的所有功能均有效。 nginxVersion 的调试输出是:

ok: [server] => {
    "var": {
        "nginxVersion": {
            "changed": true,
            "cmd": "/usr/local/nginx/sbin/nginx -v 2>&1",
            "delta": "0:00:00.003752",
            "end": "2015-09-25 16:45:26.500409",
            "invocation": {
                "module_args": "/usr/local/nginx/sbin/nginx -v 2>&1",
                "module_name": "shell"
            },
            "rc": 0,
            "start": "2015-09-25 16:45:26.496657",
            "stderr": "",
            "stdout": "nginx version: nginx/1.8.0",
            "stdout_lines": [
                "nginx version: nginx/1.8.0"
            ],
            "warnings": []
        }
    }
}

根据文档,我是对的,我错过了什么简单的技巧?

尝试:

when: nginxVersion.stdout != 'nginx version: nginx/1.8.0'

when: '"nginx version: nginx/1.8.0" not in nginxVersion.stdout'

因为 var 是一个 json 字符串,你可以将它解析为 json 并访问它的键。

set_fact:
  var_json: "{{ var.stdout|from_json }}"

然后访问 json 并获取您想要的值。

when: var_json.nginxVersion.stdout == 'nginx version: nginx/1.8.0'

检查此 link:https://gist.github.com/justinhennessy/28e82c2ec05f9081786a