Skip to content

Instantly share code, notes, and snippets.

@pwmcintyre
Last active April 15, 2021 00:46
Show Gist options
  • Save pwmcintyre/38ac32e93b83634944e32c3d0f6c7b8c to your computer and use it in GitHub Desktop.
Save pwmcintyre/38ac32e93b83634944e32c3d0f6c7b8c to your computer and use it in GitHub Desktop.
bulk purge AWS CloudFromation stacks

Simple Stack Purge

Install

npm i

Run

Just keep running... things will fail depending on your dependancy graph

AWS_PROFILE=nbos AWS_REGION=us-west-2 node .

Tricky Things

  • non-empty S3 buckets (easy to delete via Console or Python)
const AWS = require('aws-sdk')
const cloudformation = new AWS.CloudFormation();
const StackNameFilter = /^ris-[^-]+-[1-9]([0-9])*-.*$/
const StackStatusFilter = [
"CREATE_IN_PROGRESS",
"CREATE_FAILED",
"CREATE_COMPLETE",
"ROLLBACK_IN_PROGRESS",
"ROLLBACK_FAILED",
"ROLLBACK_COMPLETE",
// "DELETE_IN_PROGRESS",
"DELETE_FAILED",
// "DELETE_COMPLETE",
"UPDATE_IN_PROGRESS",
"UPDATE_COMPLETE_CLEANUP_IN_PROGRESS",
"UPDATE_COMPLETE",
"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",
]
async function purge () {
let stacks = []
// list stacks
let NextToken = undefined
while (true) {
console.log("discovering stacks ...", { count: stacks.length })
const result = await cloudformation.listStacks({ NextToken, StackStatusFilter }).promise()
const names = result.StackSummaries.map( s => s.StackName )
stacks.push(...names)
if ( !result.NextToken ) break
NextToken = result.NextToken
}
console.log("discovered stacks", { count: stacks.length, stacks })
// filter
stacks = stacks.filter( name => name.match(StackNameFilter) )
console.log("filtered stacks", { count: stacks.length, stacks })
// delete
const results = stacks.map( StackName => {
return cloudformation.deleteStack({ StackName }).promise()
.then( _ => console.log("deleting", { StackName }) )
})
await Promise.all( results )
}
async function main () {
await purge()
}
main().then(
console.log,
console.error,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment