Don't mark something as changed when determini

2019-06-17 02:55发布

问题:

I have the following role in my Ansible playbook to determine the installed version of Packer and conditionally install it if it doesn't match the version of a local variable:

---
#  detect packer version
 - name: determine packer version
   shell: /usr/local/bin/packer -v || true
   register: packer_installed_version
 - name: install packer cli tools
   unarchive:
       src: https://releases.hashicorp.com/packer/{{ packer_version }}/packer_{{ packer_version }}_linux_amd64.zip
       dest: /usr/local/bin
       copy: no
   when: packer_installed_version.stdout != packer_version

The problem/annoyance is that Ansible marks this step as having "changed":

I'd like gather this fact without marking something as changed so I can know reliably at the end of my playbook execution if anything has, in fact, changed.

Is there a better way to go about what I'm doing above?

回答1:

From the Ansible docs:

Overriding The Changed Result New in version 1.3.

When a shell/command or other module runs it will typically report “changed” status based on whether it thinks it affected machine state.

Sometimes you will know, based on the return code or output that it did not make any changes, and wish to override the “changed” result such that it does not appear in report output or does not cause handlers to fire:

tasks:

  - shell: /usr/bin/billybass --mode="take me to the river"
    register: bass_result
    changed_when: "bass_result.rc != 2"

  # this will never report 'changed' status
  - shell: wall 'beep'
    changed_when: False

In your case you would want:

---
#  detect packer version
 - name: determine packer version
   shell: /usr/local/bin/packer -v || true
   register: packer_installed_version
   changed_when: False
 - name: install packer cli tools
   unarchive:
       src: https://releases.hashicorp.com/packer/{{ packer_version }}/packer_{{ packer_version }}_linux_amd64.zip
       dest: /usr/local/bin
       copy: no
   when: packer_installed_version.stdout != packer_version


标签: ansible