Ansible condition when string not matching

2019-03-10 03:56发布

问题:

I am trying to write an Ansible playbook that only compiles Nginx if it's not already present and at the current version. However it compiles every time which is undesirable.

This is what I have:

- 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

The script all works apart from the fact that it runs the shell script every time to compile Nginx. The debug output for nginxVersion is:

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": []
        }
    }
}

According to the documentation I am on the right lines, what simple trick am I missing?

回答1:

Try:

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

or

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


回答2:

Since var is a json string you can parse it to json and access it's keys.

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

Then access the json and get the value you want.

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

checkout this link: https://gist.github.com/justinhennessy/28e82c2ec05f9081786a