Automate deletion of AWS CloudFormation stacks and associated resources - AWS Prescriptive Guidance
Services or capabilities described in AWS documentation might vary by Region. To see the differences applicable to the AWS European Sovereign Cloud Region, see the AWS European Sovereign Cloud User Guide.

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 is a widely used service for managing cloud infrastructure as code (IaC). When you use CloudFormation, you manage related resources as a single unit called a stack. You create, update, and delete a collection of resources by creating, updating, and deleting stacks.

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

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 phases that discover, process, and delete CloudFormation stacks and their associated resources.

The diagram shows the following workflow:

  1. 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.

    Note

    The 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.

  2. 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 DeletionProtectionEnabled setting for DynamoDB tables to False. In the command-line interface, for each resource, you receive a prompt asking if you want to override the constraint.

  3. 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.

  4. 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.

    Note

    The 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

  • Click is a Python tool that helps you create command line interfaces.

  • Poetry is a tool for dependency management and packaging in Python.

  • Pyenv is a tool that helps you manage and switch between versions of Python.

  • Python is a general-purpose computer programming language.

Code repository

The code for this pattern is available in the GitHub cloudformation-stack-cleanup repository.

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

TaskDescriptionSkills required

Clone the repository.

  1. Create a folder in your virtual environment. Name it with your project name.

  2. Open a terminal on your local machine, and navigate to this folder.

  3. Enter the following command to clone the cloudformation-stack-cleanup repository to your project directory:

    git clone https://github.com/aws-samples/cloudformation-stack-cleanup.git
DevOps engineer

Install Poetry.

Follow the instructions (Poetry documentation) to install Poetry in the target virtual environment.

DevOps engineer

Install dependencies.

  1. Enter the following command to navigate to the project directory:

    cd cloudformation-stack-cleanup
  2. Enter the following command:

    poetry install eval $(poetry env activate)

    This installs all of the required dependencies, such as Boto3, click, and the source code for the CloudFormation CLI.

DevOps engineer
TaskDescriptionSkills required

Create functions that gather, pre-process, and delete the target resources.

  1. In the cloned repository, enter the following command to navigate to the cli directory:

    cd cfncli/cli
  2. Open the cleanup_environment.py file.

  3. Create a new Python function that gathers the type of resource that you want to modify. For an example, see the gather_ddb_tables function in this file.

  4. Create a new Python function that overrides the service constraints for the target resource. For an example, see the remove_ddb_deletion_protection function in this file.

  5. Create a new Python function that collects unmanaged target resources. For an example, see the gather_log_groups function in this file.

  6. Create a new Python function that deletes unmanaged target resources. For an example, see the delete_log_group function in this file.

  7. Save and close the cleanup_environment.py file.

DevOps engineer, Python
TaskDescriptionSkills required

Create a CloudFormation stack.

  1. Navigate to the project directory.

  2. Enter the following command to create a CloudFormation stack that provisions a security group, two Amazon S3 buckets, an AWS KMS key, and a DynamoDB table. Replace <VPCID> with your VPC ID.

    aws cloudformation create-stack \ --stack-name sampleforcleanup-Stack \ --template-body file://samples/sample-cfn-stack.yaml \ --parameters ParameterKey=VpcId,ParameterValue=<VPCID> \ --region us-east-1
AWS DevOps

Create a Systems Manager parameter.

Enter the following command to create a Systems Manager parameter that isn't provisioned through CloudFormation:

aws ssm put-parameter \ --name "/sampleforcleanup/database/password" \ --value "your_db_password" \ --type "SecureString" \ --description "Database password for my app" \ --tier "Standard" \ --region "us-east-1"
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 <REGION> and <ACCOUNT_ID> with your AWS Region and account ID.

aws s3api create-bucket \ --bucket sampleforcleanup-unmanagedbucket-<REGION>-<ACCOUNT_ID> \ --region us-east-1
AWS DevOps
TaskDescriptionSkills required

Delete the CloudFormation stack.

  1. Enter the following command to delete the sample CloudFormation stack, Systems Manager parameter, and Amazon S3 bucket that you created:

    cfncli --region us-east-1 \ dev cleanup-env \ --prefix-list sampleforcleanup
  2. When prompted, enter Y to continue.

Amazon S3 delivers server access logs on a best-effort basis, usually within a few hours. If a log arrives in sampleforcleanup-access-logs-<REGION>-<ACCOUNT_ID> after cfncli empties it, the stack deletion fails because the bucket isn't empty. Run the command again. The cfncli tool selects the stack in DELETE_FAILED status, empties the bucket again, and retries the deletion.

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

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']