Automating enabling termination Protection for AWS Cloudformation

Alien
1 min readJan 4, 2024

AWS Cloudformation has evolved as one of integral part of devops architecture of any team. It is good practice to enable termination protection. You can automate the process by using EventBrige Rules -> Lambda Setup to automate this process.

Steps

  1. Create a Lambda function with Python Run time. Add the following code in the code editor
import boto3
import logging

logger = logging.getLogger()
logger.setLevel(logging.INFO)
client = boto3.client("cloudformation")


def lambda_handler(event, context):
paginator = client.get_paginator("describe_stacks")
response_iterator = paginator.paginate()
for page in response_iterator:
for objects in page["Stacks"]:
if "ParentId" in objects:
logger.info("Skipping %s as it is a Nested Stack", objects["StackName"])
else:
response = client.update_termination_protection(
EnableTerminationProtection=True, StackName=objects["StackName"]
)
logger.info("%s response %s", objects["StackName"], response)

return {"status": 200}

2. Add policy to Lambda function so it can update the CFN

3. Add an Event Bridge trigger using AWS Lambda Console with Schedule expression: cron(0 18 ? * FRI *) and Event bus: default

This will trigger lambda every Friday at 6pm.

--

--