Ansible - On error, exit role and run cleanup

2019-03-03 08:31发布

问题:

I'm trying to spin up an AWS deployment environment in Ansible, and I want to make it so that if something fails along the way, Ansible tears down everything on AWS that has been spun up so far. I can't figure out how to get Ansible to throw an error within the role

For example:

<main.yml>
- hosts: localhost
  connection: local
  roles:
    - make_ec2_role
    - make_rds_role 
    - make_s3_role

   2. Then I want it to run some code based on that error here.

<make_rds_role>
    - name: "Make it"
    - rds:
        params: etc <-- 1. Let's say it fails in the middle here

I've tried:

- name: this command prints FAILED when it fails
  command: /usr/bin/example-command -x -y -z
  register: command_result
  failed_when: "'FAILED' in command_result.stderr"

As well as other things on within the documentation, but what I really want is just a way to use something like the "block" and "rescue" commands , but as far as I can tell that only works within the same book and on plays, not roles. Does anyone have a good way to do this?

回答1:

Wrap tasks inside your roles into block/rescue thing.
Make sure that rescue block has at least one task – this way Ansible will not mark the host as failed.
Like this:

- block:
    - name: task 1

    ... # something bad may happen here

    - name: task N

  rescue: 
    - assert: # we need a dummy task here to prevent our host from being failed
        that: ansible_failed_task is defined

Recent versions of Ansible register ansible_failed_task and ansible_failed_result when hit rescue block.
So you can do some post_tasks in your main.yml playbook like this:

  post_tasks:
    - debug:
        msg: "Failed task: {{ ansible_failed_task }}, failed result: {{ ansible_failed_result }}"
      when: ansible_failed_task is defined

But be warned that this trick will NOT prevent other roles from executing.
So in your example if make_rds_role fails ansible will apply make_s3_role and run your post_tasks afterwards.
If you need to prevent it, add some checking for ansible_failed_task fact in the beginning of each role or something.