Automate deletion of AWS CloudFormation stacks and associated resources
SANDEEP SINGH and James Jacob, Amazon Web Services
Summary
This is a sample pattern, for non-production usage. You should work with your security and legal teams to meet your organizational security, regulatory and compliance requirements before deployment.
AWS CloudFormation
Sometimes, you no longer need the resources in a CloudFormation stack. Depending on the resources and their configurations, deleting a stack and its associated resources can be complicated. In real-world production systems, deletions sometimes fail or take a long time because of conflicting conditions or restrictions that CloudFormation can't override. Careful planning and execution help you delete all resources properly, efficiently, and consistently. This pattern describes how to set up a framework that helps you manage the deletion of CloudFormation stacks that involve the following complexities:
Resources with delete protection – Some resources might have delete protection enabled. Common examples are Amazon DynamoDB
tables and Amazon Simple Storage Service (Amazon S3) buckets. Delete protection prevents automated deletion, such as deletion through CloudFormation. If you want to delete these resources, you must manually or programmatically override or temporarily disable the delete protection. You should carefully consider the implication of deleting these resources before proceeding. Resources with retention policies – Certain resources, such as AWS Key Management Service (AWS KMS) keys and Amazon S3 buckets, might have retention policies that specify how long they must be retained after you request deletion. AWS KMS keys have a waiting period of 7 to 30 days before deletion, and Amazon S3 Object Lock retention prevents object versions from being deleted until the retention period expires. Account for these waiting periods in your cleanup strategy to help maintain compliance with organizational policies and regulatory requirements.
Delayed deletion of Lambda functions that are attached to a VPC – Deleting an AWS Lambda
function that is attached to a virtual private cloud (VPC) can take up to 20 minutes, depending on the multiple interconnected dependencies involved in the process. If you detach the function from the VPC before deleting the stack, you can reduce this delay to under 1 minute. Resources not directly created by CloudFormation – In certain application designs, resources might be created outside of the original CloudFormation stack, either by the application itself or by resources provisioned through the stack. The following are two examples:
CloudFormation might provision an Amazon Elastic Compute Cloud (Amazon EC2)
instance that runs a user data script. Then, this script might create an AWS Systems Manager parameter to store application-related data. This parameter is not managed through CloudFormation. CloudFormation might provision a Lambda function that automatically generates an Amazon CloudWatch Logs
group for storing logs. This log group is not managed through CloudFormation.
Even though these resources aren't directly managed by CloudFormation, they often need to be cleaned up when the stack is deleted. If left unmanaged, they can become orphaned and lead to unnecessary resource consumption.
Although these guardrails can cause complexity, they are intentional and critical. Allowing CloudFormation to override all constraints and indiscriminately delete resources could lead to detrimental and unforeseen consequences in many scenarios. However, as a DevOps or cloud engineer who is responsible for managing the environment, there are times when overriding these constraints might be necessary, particularly in development, testing, or staging environments.
Targeted business outcomes
By implementing this framework, you can achieve the following benefits:
Cost management – Regular and efficient cleanup of temporary environments, such as end-to-end or user-acceptance testing environments, helps prevent resources from running longer than necessary. This can help reduce costs.
Security – Automated cleanup of outdated or unused resources can help reduce the attack surface in your AWS environment.
Operational efficiency – Regular and automated cleanup can provide the following operational benefits:
Automated scripts that remove old log groups or empty Amazon S3 buckets can improve operational efficiency by keeping the environment clean and manageable.
Quickly deleting and recreating stacks supports rapid iteration for design and implementation, which can lead to a more robust and resilient architecture.
Regularly deleting and rebuilding environments can help you identify and fix potential issues and validate that the infrastructure is designed to withstand real-world scenarios.
Prerequisites and limitations
Prerequisites
An active AWS account
Python version 3.13 or later, installed
pipx, installed
AWS Command Line Interface (AWS CLI), installed
and configured for a non-production account
Limitations
The framework uses a naming convention to identify the resources to delete. The sample code in this pattern uses a prefix for the resource name, but you can define your own naming convention. The framework doesn't identify or delete resources that don't use this naming convention.
The framework deletes every resource in the selected AWS Region whose name starts with a specified prefix. Use prefixes that only your temporary environments use.
AWS CloudFormation deletes stack resources with your credentials unless the stack has a service role
. The credentials need permission to delete the resources in your stacks.
Architecture
The following diagram shows how this framework identifies the target CloudFormation stack and the additional resources associated with it.

The diagram shows the following workflow:
Gather resources – The automation framework uses a naming convention to return all relevant CloudFormation stacks, Amazon Elastic Container Registry (Amazon ECR) repositories, and Amazon Simple Storage Service (Amazon S3) buckets. It then returns the DynamoDB tables in those stacks.
NoteThe functions for this stage use paginators
, a feature in Boto3 that abstracts the process of iterating over a truncated API result set. This helps make sure that the functions process all resources. To further optimize performance, consider applying server-side filtering or using JMESPath to perform client-side filtering. Pre-processing – The automation framework identifies and addresses the service constraints that you must override to allow CloudFormation to delete the resources. For example, it changes the
DeletionProtectionEnabledsetting for DynamoDB tables toFalse. In the command-line interface, for each resource, you receive a prompt asking if you want to override the constraint.Delete stack – The automation framework deletes the CloudFormation stack. In the command-line interface, you receive a prompt asking if you want to delete the stack.
Post-processing – The automation framework deletes any related resources that CloudFormation did not directly provision as part of the stack. Examples of these resource types include Systems Manager parameters and CloudWatch log groups. Separate functions gather these resources, pre-process them, and then delete them. In the command-line interface, for each resource, you receive a prompt asking if you want to delete the resource.
NoteThe functions for this stage use paginators
, a feature in Boto3 that abstracts the process of iterating over a truncated API result set. This helps make sure that the functions process all resources. To further optimize performance, consider applying server-side filtering or using JMESPath to perform client-side filtering.
Automation and scale
If your CloudFormation stack includes other resources that the sample code does not include, or if the stack has a constraint that this pattern does not address, you can adapt the automation framework for your use case. Follow the same methodology of gathering resources, pre-processing, deleting the stack, and then post-processing.
Tools
AWS services
AWS CloudFormation
helps you set up AWS resources, provision them quickly and consistently, and manage them throughout their lifecycle across AWS accounts and AWS Regions. AWS SDK for Python (Boto3)
is a software development kit that helps you integrate your Python application, library, or script with AWS services.
Other tools
Code repository
The code for this pattern is available in the GitHub cloudformation-stack-cleanup
Best practices
Tag resources for easy identification – Implement a tagging strategy
to identify resources that you create for different environments and purposes. Tags can simplify the cleanup process by helping you filter resources based on their tags. Set up resource lifecycles – Define resource lifecycles to automatically delete resources after a specified period. This practice helps ensure that temporary environments don't become permanent cost liabilities.
Epics
| Task | Description | Skills required |
|---|---|---|
Clone the repository. |
| DevOps engineer |
Install Poetry. | Follow the instructions | DevOps engineer |
Install dependencies. |
| DevOps engineer |
| Task | Description | Skills required |
|---|---|---|
Create functions that gather, pre-process, and delete the target resources. |
| DevOps engineer, Python |
| Task | Description | Skills required |
|---|---|---|
Create a CloudFormation stack. |
| AWS DevOps |
Create a Systems Manager parameter. | Enter the following command to create a Systems Manager parameter that isn't provisioned through CloudFormation:
| AWS DevOps |
Create an Amazon S3 bucket. | Enter the following command to create an Amazon S3 bucket that you don't provision through CloudFormation: Replace
| AWS DevOps |
| Task | Description | Skills required |
|---|---|---|
Delete the CloudFormation stack. |
Amazon S3 delivers server access logs on a best-effort basis, usually within a few hours | AWS DevOps |
Validate resource deletion. | In the output, confirm that all of the sample resources have been deleted. For a sample output, see the Additional resources section of this pattern. | AWS DevOps |
Related resources
Delete a stack
(CloudFormation documentation) Troubleshooting CloudFormation
(CloudFormation documentation) Giving Lambda functions access to resources in an Amazon VPC
(Lambda documentation) How do I delete an AWS CloudFormation stack that's stuck in DELETE_FAILED status?
(AWS Knowledge Center)
Additional information
The following is a sample output from the cfncli command:
cfncli -r us-east-1 dev cleanup-env --prefix-list sampleforcleanup Cleaning up: ['sampleforcleanup'] in <ACCOUNT_ID>:us-east-1 Do you want to proceed? [y/N]: y The following S3 buckets will be emptied sampleforcleanup-access-logs-us-east-1-<ACCOUNT_ID> sampleforcleanup-unmanagedbucket-us-east-1-<ACCOUNT_ID> Do you want to proceed with emptying these S3 buckets? [y/N]: y Emptied S3 bucket: sampleforcleanup-access-logs-us-east-1-<ACCOUNT_ID> Emptied S3 bucket: sampleforcleanup-unmanagedbucket-us-east-1-<ACCOUNT_ID> No ECR repositories No Lambda functions in VPC The following DynamoDB tables will have their deletion protection removed: sampleforcleanup-MyDynamoDBTable-us-east-1-<ACCOUNT_ID> Do you want to proceed with removing deletion protection from these tables? [y/N]: y Deletion protection disabled for DynamoDB table 'sampleforcleanup-MyDynamoDBTable-us-east-1-<ACCOUNT_ID>'. The following CloudFormation stacks will be deleted: sampleforcleanup-Stack Do you want to proceed with deleting these CloudFormation stacks? [y/N]: y Initiated deletion of CloudFormation stack: sampleforcleanup-Stack Waiting for stack sampleforcleanup-Stack to be deleted... CloudFormation stack sampleforcleanup-Stack deleted successfully. The following s3_buckets will be deleted: sampleforcleanup-unmanagedbucket-us-east-1-<ACCOUNT_ID> Do you want to proceed with deleting these s3_buckets? [y/N]: y Deleted S3 bucket: sampleforcleanup-unmanagedbucket-us-east-1-<ACCOUNT_ID> The following ssm_params will be deleted: /sampleforcleanup/database/password Do you want to proceed with deleting these ssm_params? [y/N]: y Deleted SSM Parameter: /sampleforcleanup/database/password Cleaned up: ['sampleforcleanup']