Cloud Architecture

Using Python to Tear Down CloudFormation Stacks with a Single Command

March 10, 2023

In a previous article I detailed how you can use GitHub actions to set up a CI/CD pipeline that automatically provisions your cloud infrastructure using CloudFormation. You can use that approach to spin up testing, staging and production environments quickly.

Spin up and tear down

Unlike Terraform's "destroy" command, CloudFormation doesn't provide an out-of-the-box way to automatically tear-down your entire collection of stacks. And that's a bummer, especially when you are still developing and you don't want to pay for unused resources.

The AWS CLI allows you to delete individual and even multiple CloudFormation stacks at the same time.

But the downside of this approach, is that all the stacks that you target with this command will try to delete themselves at the same time. And this can be a problem when one stack is referencing the other.

Automating this using Python

To overcome this, I decided to write a little Python script. The script first retrieves a list of stacks. Next it deletes the most recent stack. Once deleted it moves on to the next one.

Pre-requisites

To run this script you need the following:

1. AWS CLI installed with the right AWS account profile selected.

2. Python installed.

Running the script

To run the script, simply type:

python3 destroy-all-cloudformation-stacks.py

That's it! Hopefully this save you a lot of time and resources.

About the author
Support

I'm an AWS certified cloud architect from New York, who loves writing about DevSecOps, Infrastructure as Code and Serverless. Having run a tech company myself for years, I love helping other start-up scale using the latest cloud services.

Join my mailing list

Stay up to date with everything Skripted.

Sign up for periodic updates on #IaC techniques, interesting AWS services and serverless.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.