sls-stage-destroyer
v1.0.8
Published
Intelligent AWS CloudFormation stack destroyer with S3 cleanup and retry logic for serverless applications
Downloads
19
Maintainers
Readme
Serverless Stage Destroyer
A powerful CLI tool to safely destroy AWS CloudFormation stacks for a given stage, including automatic S3 bucket cleanup.
🚀 Installation
Global Installation (Recommended)
npm install -g sls-stage-destroyerLocal Installation
npm install sls-stage-destroyerOne-time Usage
npx sls-stage-destroyer <stage-name>📋 Usage
Basic Commands
# Destroy all stacks for a stage
destroy-stage my-test-stage
# Or use the alias
sls-destroy my-test-stage
# Different region
destroy-stage dev-branch --region us-west-2📋 Usage
Basic Usage
# Destroy all stacks for a test stage
./scripts/destroy-stage.sh my-test-stage
# Destroy stacks in a different region
./scripts/destroy-stage.sh dev-branch --region us-west-2Advanced Options
# Skip confirmation prompt (dangerous!)
destroy-stage temp-stage --no-verify
# Don't wait for stack deletion to complete
destroy-stage temp-stage --no-wait
# Increase retry attempts for problematic stacks
destroy-stage problematic-stage --retries 5
# Use filters for more targeted destruction
destroy-stage temp --filter Environment=testing --filter Team=backend
# Combine options
destroy-stage temp-stage --region us-west-2 --no-verify --no-wait --retries 2Command Line Options
--region <region>- AWS region (default: us-east-1)--no-verify- Skip confirmation prompt--no-wait- Don't wait for stack deletion to complete--retries <count>- Maximum retry attempts (default: 3)--filter <key=value>- Additional tag filters (can be used multiple times)--help- Show help message--version- Show version information
🛡️ Safety Features
Protected Stage Names
The script automatically prevents destruction of protected stages:
prod,production,master
Confirmation Required
Unless --no-verify is used, the script will:
- List all stacks to be destroyed
- Require you to type the exact stage name to confirm
Termination Protection Check
The script checks for and prevents deletion of stacks with termination protection enabled.
🧹 What It Does
- Finds all stacks tagged with
STAGE: <stage-name> - Empties S3 buckets associated with each stack:
- Suspends versioning
- Applies deny policy to prevent new uploads
- Deletes all object versions and delete markers
- Deletes CloudFormation stacks with intelligent retry logic:
- Exponential backoff for transient failures
- Automatic recovery for stacks in failed states
- Detailed error classification and reporting
- Waits for completion (unless
--no-waitis specified) - Reports results with manual intervention guidance
📊 Output
The script provides detailed, emoji-rich output showing:
- Stacks found for the stage
- S3 buckets being emptied
- Stack deletion progress
- Final summary of successful/failed deletions
⚠️ Prerequisites
- AWS CLI configured with appropriate permissions
- Node.js (version 18+ recommended)
- AWS SDK for JavaScript v3 dependencies (already in package.json)
🔧 Required AWS Permissions
Your AWS credentials need the following permissions:
cloudformation:DescribeStackscloudformation:ListStackResourcescloudformation:DeleteStacks3:ListBuckets3:DeleteObjects3:PutBucketPolicys3:PutBucketVersionings3:HeadBucket
🚨 Danger Zones
Permanent Deletion
This script PERMANENTLY DELETES infrastructure and data. There is no undo.
Protected Stages
Double-check that you're not trying to delete production infrastructure.
CI/CD Usage
When CI=true environment variable is set, the confirmation prompt is automatically skipped.
🔄 Error Handling & Recovery
The script includes sophisticated error handling for common CloudFormation issues:
Automatic Retry Logic
- Transient failures: Automatic retry with exponential backoff
- Internal failures: Like
"errorMsg" is nullerrors get retried - Service issues: Throttling, timeouts, and service unavailable errors
- Configurable retries: Use
--max-retriesto adjust retry count
Recovery Strategies
- DELETE_FAILED stacks: Automatically attempts to continue deletion
- Already deleted: Detects and handles stacks that no longer exist
- Status checking: Identifies stack states requiring manual intervention
Manual Intervention Guidance
When stacks can't be automatically recovered, the script provides:
- Clear identification of problematic stacks
- Specific AWS Console steps to resolve issues
- Common resolution strategies for different error types
🛠️ Troubleshooting
"No stacks found"
- Verify the stage name is correct
- Check that stacks are properly tagged with
STAGE: <stage-name> - Ensure you're in the correct AWS region
"Termination protection enabled"
Disable termination protection in the AWS Console or CLI before running the script.
"Access denied" errors
Verify your AWS credentials have the required permissions listed above.
Internal CloudFormation Failures
Cannot invoke "String.contains(java.lang.CharSequence)" because "errorMsg" is null- Solution: Script automatically retries these errors
- Manual: If retries fail, try deleting the stack via AWS Console
- Last resort: Contact AWS Support for persistent internal failures
Stack in DELETE_FAILED State
- Automatic: Script detects and attempts to continue deletion
- Manual: Use AWS Console → Stack Actions → Continue Delete Stack
- Advanced: Skip problematic resources during deletion
📝 Examples
# Standard usage with confirmation
destroy-stage feature-branch-123
# CI/CD usage (no confirmation)
destroy-stage temp-123 --no-verify
# Quick cleanup without waiting
destroy-stage old-test --no-wait
# Different region
destroy-stage eu-test --region eu-west-1
# Advanced filtering
destroy-stage dev --filter Environment=testing --filter Owner=team-a🔄 GitHub Actions Integration
Use sls-stage-destroyer in your GitHub Actions workflows for automated cleanup:
PR Cleanup Workflow
Create .github/workflows/cleanup-pr.yml:
name: Cleanup PR Environment
on:
pull_request:
types: [closed]
jobs:
cleanup:
runs-on: ubuntu-latest
steps:
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v4
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: us-east-1
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
- name: Install Stage Destroyer
run: npm install -g sls-stage-destroyer
- name: Destroy PR Environment
run: |
destroy-stage "pr-${{ github.event.number }}" \
--no-verify \
--retries 3
env:
CI: trueManual Cleanup Workflow
Create .github/workflows/destroy-stage.yml:
name: Destroy Stage
on:
workflow_dispatch:
inputs:
stage_name:
description: 'Stage name to destroy'
required: true
type: string
aws_region:
description: 'AWS Region'
required: false
default: 'us-east-1'
type: string
jobs:
destroy-stage:
runs-on: ubuntu-latest
steps:
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v4
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{ inputs.aws_region }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
- name: Install Stage Destroyer
run: npm install -g sls-stage-destroyer
- name: Destroy Stage
run: |
destroy-stage "${{ inputs.stage_name }}" \
--region ${{ inputs.aws_region }} \
--no-verify \
--retries 5
env:
CI: trueRequired GitHub Secrets
Add these secrets to your GitHub repository:
AWS_ACCESS_KEY_ID- Your AWS access keyAWS_SECRET_ACCESS_KEY- Your AWS secret key
GitHub Variables (Optional)
AWS_REGION- Default AWS region for your workflows
🚀 Programmatic Usage
Use the package in your Node.js applications:
import StageDestroyer from 'sls-stage-destroyer';
const destroyer = new StageDestroyer('us-east-1');
destroyer.maxRetries = 5;
await destroyer.destroy('my-stage', {
verify: false, // skip confirmation
wait: true, // wait for completion
filters: [ // additional filters
{ Key: 'Environment', Value: 'testing' }
]
});