How to prevent 'changed' flag when 're

2019-02-11 16:01发布

问题:

I have a register task to test for the installation of a package:

tasks:
  - name: test for nginx
    command: dpkg -s nginx-common
    register: nginx_installed

Every run it gets reported as a "change":

TASK: [test for nginx] ********************************************************
changed: [vm1]

I don't regard this as a change... it was installed last run and is still installed this run. Yeah, not a biggy, just one of those untidy OCD type issues.

So am I doing it wrong? Is there some way to use register without it always being regarded as a change?

The [verbose] output is untidy, but the only way I've found to get the correct return code.

TASK: [test for nginx] ******************************************************** changed: [vm1] => {"changed": true, "cmd": ["dpkg", "-s", "nginx-common"], "delta": "0:00:00.010231", "end": "2014-05-30 12:16:40.604405", "rc": 0, "start": "2014-05-30 12:16:40.594174", "stderr": "", "stdout": "Package: nginx-common\nStatus: install ok ... \nHomepage: http://nginx.net"}

回答1:

It’s described in official documentation here.

tasks:
  - name: test for nginx
    command: dpkg -s nginx-common
    register: nginx_installed
    changed_when: false


回答2:

It is the command module causing the changed state, not the register parameter.

You can set changed_when: to something that is only true when something changed (also look at failed_when). If your task don't change anything, you might want to set check_mode as well. (Especially if other steps depend on the value)

This gives:

tasks:
  - name: test for nginx
    command: dpkg -s nginx-common
    register: nginx_installed
    changed_when: False
    failed_when: False  # dpkg -s returns 1 when packages is not found
    check_mode: yes # this can safely run in check_mode


标签: ansible