There are a couple of ways to remove/delete a set of cloud formation stacks. Some of them are given as follows.
- Use AWS CLI and execute a PowerShell(windows)/bash(Linux) script.
- Use AWS SDK with a related programming language
Here I have explained to you how to remove/delete a set of stacks based on specified conditions using AWS SDK(boto3) for Python (option 2).
import re
import boto3
client = boto3.client('cloudformation')
#list all the stacks excepts 'DELETED_STACKS'
response = client.list_stacks(
StackStatusFilter=[
'CREATE_IN_PROGRESS','CREATE_FAILED','CREATE_COMPLETE',
'ROLLBACK_IN_PROGRESS','ROLLBACK_FAILED','ROLLBACK_COMPLETE',
'DELETE_IN_PROGRESS','DELETE_FAILED',
'UPDATE_IN_PROGRESS','UPDATE_COMPLETE_CLEANUP_IN_PROGRESS','UPDATE_COMPLETE','UPDATE_FAILED','UPDATE_ROLLBACK_IN_PROGRESS','UPDATE_ROLLBACK_FAILED','UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS','UPDATE_ROLLBACK_COMPLETE','REVIEW_IN_PROGRESS',
'IMPORT_IN_PROGRESS','IMPORT_COMPLETE','IMPORT_ROLLBACK_IN_PROGRESS','IMPORT_ROLLBACK_FAILED','IMPORT_ROLLBACK_COMPLETE'
]
)
#Stack name pattern
regex_pattern = "^removablestack.*"
for cfn_stack in response['StackSummaries']:
stack_name = cfn_stack['StackName']
match = re.search(regex_pattern,stack_name)
#Custome conditions can be implemented here
if match:
client.delete_stack(StackName=stack_name)
You can find the boto3 documentation here for listing all cloudformation stacks (list_stacks) and for deleting a cloudformation stack (delete_stack).