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"}
An important line there is the changed_when: false line. Typically ansible assumes that a command changes the state of the host, but changed_when lets you set a Jinja2 conditional to specify a different condition. This stops false alarms from runs that change nothing on the host, which is good for idempotency.
Ansible lets you define when a particular task has “changed” a remote node using the changed_when conditional. This lets you determine, based on return codes or output, whether a change should be reported in Ansible statistics and whether a handler should be triggered or not.
rc. Some modules execute command line utilities or are geared for executing commands directly (raw, shell, command, and so on), this field contains 'return code' of these utilities.
It’s described in official documentation here.
tasks: - name: test for nginx command: dpkg -s nginx-common register: nginx_installed changed_when: false
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With