-2

I am trying to remove all the cloudformation stacks that name starts with 'removablestack'

i am using SSM document but i am able to remove only one stack, i am not able to remove all at once. i am in a need of SSM document to remove all at once.

Tried SSM automation and even tried boto3 python script. but none helping

Raj R
  • 1

1 Answers1

0

There are a couple of ways to remove/delete a set of cloud formation stacks. Some of them are given as follows.

  1. Use AWS CLI and execute a PowerShell(windows)/bash(Linux) script.
  2. Use AWS SDK with a related programming language

Here I have explained to you how to remove/delete a set of stacks based on specified conditions using AWS SDK(boto3) for Python (option 2).

import re
import boto3

client = boto3.client('cloudformation')

#list all the stacks excepts 'DELETED_STACKS'
response = client.list_stacks(
    StackStatusFilter=[
    'CREATE_IN_PROGRESS','CREATE_FAILED','CREATE_COMPLETE',
    'ROLLBACK_IN_PROGRESS','ROLLBACK_FAILED','ROLLBACK_COMPLETE',
    'DELETE_IN_PROGRESS','DELETE_FAILED',
    'UPDATE_IN_PROGRESS','UPDATE_COMPLETE_CLEANUP_IN_PROGRESS','UPDATE_COMPLETE','UPDATE_FAILED','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'
    ]
)

#Stack name pattern
regex_pattern = "^removablestack.*"

for cfn_stack in response['StackSummaries']:
    stack_name = cfn_stack['StackName']
    match = re.search(regex_pattern,stack_name)

    #Custome conditions can be implemented here
    if match:
        client.delete_stack(StackName=stack_name)

You can find the boto3 documentation here for listing all cloudformation stacks (list_stacks) and for deleting a cloudformation stack (delete_stack).