Ansible – Continue nicely when shell exits with error

Sometimes a command gives an exit code which isn’t considered an error in your playbook. You could use “ignore_errors” but it will stand out when you run your playbook, and it’s the first thing new colleagues point out when we run a play together.

This example shows you how to use the exit code in a when clause without ansible throwing (and catching) the exception.

- name: Check if md5sum of the current  is the same
  shell: 'md5sum --check /install/md5sum_of_installer'
  register: installer_md5sum_check
  failed_when: ( installer_md5sum_check.rc not in [ 0, 1 ] )

- name: Run Installer if md5sum is different or missing
  include_role:
    name: my_install_role
  when: installer_md5sum_check.rc == 1
  ## rc 0: the md5sum output was "OK", thus was already installed
  ## rc 1: it was not the same (or the file was missing)

- name: Create md5sum for the installer
  shell: 'md5sum /install/my_installer.zip > /install/md5sum_of_installer'
  when: installer_md5sum_check.rc == 1
  ## We can only arrive here when the installer role was successfully finished

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.