Handling Failure during AMI creation

Hi guys
I have a playbook that:

  • Creates an EC2 instance
  • Provisions the instance using a few roles
  • Creates an AMI out of that instance
  • Destroys the instance after the AMI is created successfully
    Now the problem is if there’s a failure somewhere after the instance creation, let’s say npm is having issues which is quite normal or some ubuntu repository is having issues, and I run the playbook again, it will spin up a new instance. How can I handle this? Preferably a way to use the same instance if the failure happens before AMI creation part or at least automatically delete the instance if I hit an error before exiting the playbook successfully.

Here’s my current playbook:

`