cleanup-cloudformation-stacks
v1.0.0
Published
Typescript AWS cleanup script for CloudFormation Stacks
Downloads
3
Readme
CloudFormation Stack Cleaner
This is a Node.js script that uses the [@aws-sdk/client-cloudformation] package to list and delete CloudFormation stacks that match certain criteria.
Prerequisites
- You need to have Node.js and NPM installed on your machine.
- You need to have an AWS account and configure your credentials and region in your environment variables or in a configuration file. See [Setting Credentials in Node.js] for more details.
Installation
- Clone this repository or download the source code as a ZIP file.
- Navigate to the project folder and run
npm install
to install the dependencies.
Usage
- Open the
index.ts
file and edit thestackNameConfig
variable to specify the substring and position (prefix or suffix) that you want to use to filter the stacks. You can also add any exceptions that you want to exclude from the deletion. For example, if you want to delete all stacks that start withdev-
exceptdev-main
, you can use:
const stackNameConfig: StackNameConfig = {
substring: 'dev-',
substringPosition: 'prefix',
exceptions: ['dev-main']
}
How it works
- The script uses the
CloudFormationClient
class from the@aws-sdk/client-cloudformation
package to interact with the AWS CloudFormation service. It creates an instance of the client with the region specified in the constructor. - The script uses the
paginateListStacks
function from the same package to get a paginator object that can iterate over the pages of the list stacks command. It passes theStackStatusFilter
parameter to filter only the stacks that are in a complete state (created, updated, or rolled back). - The script loops over the pages of the paginator and pushes the stack summaries to an array. It then checks if the array is empty and throws an error if it is.
- The script filters the array of stack summaries by applying the
stackNameCondition
function, which checks if the stack name matches the substring and position specified in thestackNameConfig
variable and is not in the exceptions list. It also applies theisStaleStack
function, which checks if the stack has aLastUpdatedTime
property and if it is older than one day. - The script logs the filtered stack summaries and asks the user to confirm if they want to delete them. If the user enters
y
, it loops over the filtered stack summaries and calls thedeleteStack
function, which sends a delete stack command to the CloudFormation service with the stack name as the parameter. It then logs the deletion result. If the user entersn
, it exits the script.