1.0.0 • Published 6 months ago

cleanup-cloudformation-stacks v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
6 months ago

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 the stackNameConfig 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 with dev- except dev-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 the StackStatusFilter 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 the stackNameConfig variable and is not in the exceptions list. It also applies the isStaleStack function, which checks if the stack has a LastUpdatedTime 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 the deleteStack 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 enters n, it exits the script.