Skip to content

Instantly share code, notes, and snippets.

@pads
Created March 20, 2025 10:19
Show Gist options
  • Save pads/f1e86548b7a9fba6229916bfd0bd4bd1 to your computer and use it in GitHub Desktop.
Save pads/f1e86548b7a9fba6229916bfd0bd4bd1 to your computer and use it in GitHub Desktop.
Delete multiple AWS stacks at once, by prefix. Ignoring any prod/staging environments
#!/bin/bash
PREFIX=$1
EXECUTE=false
if [ -z "$1" ]; then
echo "Please supply a stack name prefix"
exit 1
fi
if echo "$PREFIX" | grep -qiE "prod|staging"; then
echo "ERROR: The prefix contains a restricted environment keyword (prod, staging)."
exit 1
fi
if [[ "$2" == "--execute" ]]; then
EXECUTE=true
fi
STACKS=$(aws cloudformation list-stacks --stack-status-filter CREATE_COMPLETE UPDATE_COMPLETE ROLLBACK_COMPLETE \
--query "StackSummaries[?starts_with(StackName, \`${PREFIX}\`)].StackName" --output text)
if [ -z "$STACKS" ]; then
echo "No stacks found with prefix: $PREFIX"
exit 0
fi
for STACK in $STACKS; do
echo "Will delete stack: $STACK"
if [ "$EXECUTE" = true ]; then
aws cloudformation delete-stack --stack-name "$STACK"
echo "Deleting stack: $STACK"
fi
done
echo "Deletion initiated for all matching stacks."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment