Recursive deletion of CloudFormation Stacks

Context

There are particularly three actions that you can apply to your CloudFormation stacks.

  • CREATE

  • UPDATE

  • DELETE

This blog focuses more on the deletion side of the Stacks. Why would you want to have an advanced deletion mechanism in place:

  • When you want to prune your dev/test environment repeatedly and start from scratch

  • When you want to save dollars by removing unnecessary resources

  • When you manage all your infrastructure from CloudFormation

  • When you want to experiment with a temporary environment

  • When you have more than 100s stacks and hard to delete the individual stacks because of hard dependencies between the stack resources.

Solution

The solution to this problem is to use a certain form of automation that provides a mechanism to select the stacks to be deleted. Selection can be done using various parameters like stack name pattern, tags, and date time frame. Here I'd like to present you the simple script that lets you recursively delete based on the stack name pattern.

How to

NOTE: Please be extremely careful while using this in production.

Syntax: DELETE_PATTERN=<pattern-string> AWS_PROFILE=<profile-name> AWS_REGION=<region|defaults to us-east-1> ./<path-to-script>

Takes 3 inputs DELETE_PATTERN, AWS_PROFILE and AWS_REGION
as an environment variable.

  • Download:
#Download
wget https://gist.githubusercontent.com/rbalman/b607040ea1f41d2ebb3c318593fa5b1f/raw/6b69ccc94dbf50fe2c1de93080d99fa34b055b7f/cfn-delete.sh
chmod +x cfn-delete.sh
  • Execute

    This will list all the name of all the stacks that are selected and prompt for approval. Then it will recursively delete all the stacks in sequential order, it will keep retrying until the stack count drops to zero.

DELETE_PATTERN=dev- AWS_PROFILE=demo AWS_REGION=us-east-1 ./cfn-delete.sh

https://gist.github.com/rbalman/b607040ea1f41d2ebb3c318593fa5b1f

Caveats

Some resources may not get deleted due to the limitation of CloudFormation.

  • bucket CloudFormation stack can't be deleted unless it is empty

  • resources with the DeletionPolicy: Retain will still be there.

  • Backups from the AWS Backup won't get deleted

  • Protected by the Stack Policy

  • Protected by the IAM policy

In this case you need to remove the cause of the failure and retry the deletion.