Skip to content

Instantly share code, notes, and snippets.

@fortran01
Created January 8, 2024 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fortran01/8d22a30d8dcc8edb951fe40fbac9e724 to your computer and use it in GitHub Desktop.
Save fortran01/8d22a30d8dcc8edb951fe40fbac9e724 to your computer and use it in GitHub Desktop.
"""
This script is used to manage AWS CloudFormation stacks.
It allows the user to:
- Set the AWS region
- Check the account ID
- List all the stacks that start with "AWSAccelerator" and have StackStatus either "UPDATE_COMPLETE" or "CREATE_COMPLETE"
- Sort these stacks according to their CreationTime
- Remove termination protection from these stacks.
- Delete these stacks one by one
"""
import boto3
TARGET_ACCOUNT_ID = 'xxx'
def set_region():
region = input("Enter AWS region: (default: ca-central-1) ")
if not region:
region = 'ca-central-1'
boto3.setup_default_session(region_name=region)
def check_account_id():
sts = boto3.client('sts')
account_id = sts.get_caller_identity()["Account"]
if account_id != TARGET_ACCOUNT_ID:
print("Invalid account id. Exiting...")
exit()
# Print the account id
print(account_id)
def list_stacks():
# Create a client
client = boto3.client('cloudformation')
# List all stacks
response = client.list_stacks()
# print(response)
# Filter stacks that start with "AWSAccelerator" and have StackStatus either "UPDATE_COMPLETE" or "CREATE_COMPLETE"
stacks = [
stack for stack in response['StackSummaries']
if stack['StackName'].startswith('AWSAccelerator')
and (stack['StackStatus'] == 'UPDATE_COMPLETE' or stack['StackStatus'] == 'CREATE_COMPLETE')
]
# Sort stacks according to CreationTime. Newest is last.
stacks.sort(key=lambda x: x['CreationTime'], reverse=True)
# Print the sorted stack names
for stack in stacks:
print(stack['StackName'])
return stacks
def remove_termination_protection(stacks):
# Create a client
client = boto3.client('cloudformation')
# Iterate over stacks and remove termination protection
for stack in stacks:
client.update_termination_protection(
StackName=stack['StackName'],
EnableTerminationProtection=False
)
print(f"Termination protection removed from stack: {stack['StackName']}")
def delete_stacks(stacks):
# Create a client
client = boto3.client('cloudformation')
# Iterate over stacks and delete them one by one
for stack in stacks:
print(f"Deleting stack: {stack['StackName']}")
client.delete_stack(
StackName=stack['StackName']
)
# Wait for the stack to be deleted
waiter = client.get_waiter('stack_delete_complete')
waiter.wait(
StackName=stack['StackName']
)
print(f"Stack deleted: {stack['StackName']}")
if __name__ == '__main__':
set_region()
check_account_id()
stacks = list_stacks()
remove_termination_protection(stacks)
delete_stacks(stacks)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment