To add an AWS Custom Resource to CloudFormation template and provide an AWS Lambda Function

0

Hi AWS,

I have faced this issue many a times i.e. A CloudFormation stack creates an Amazon S3 bucket. When the stack is deleted, an error occurs because the bucket is not empty.

How can the CloudFormation stack be modified to delete the contents of the bucket when the stack is deleted.

Can you help me with the Custom Resource?

2 回答
1

The site below has a Lambda sample that deletes objects in an S3 bucket.
https://stackoverflow.com/questions/40383470/can-i-force-cloudformation-to-delete-non-empty-s3-bucket
Only the "requests" module has changed.
Create a Lambda function with the code below.
Create a "requests" layer in your Lambda function.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import boto3
import requests


def lambda_handler(event, context):
    try:
        bucket = event['ResourceProperties']['BucketName']

        if event['RequestType'] == 'Delete':
            s3 = boto3.resource('s3')
            bucket = s3.Bucket(bucket)
            for obj in bucket.objects.filter():
                s3.Object(bucket.name, obj.key).delete()

        sendResponseCfn(event, context, "SUCCESS")
    except Exception as e:
        print(e)
        sendResponseCfn(event, context, "FAILED")


def sendResponseCfn(event, context, responseStatus):
    response_body = {'Status': responseStatus,
                     'Reason': 'Log stream name: ' + context.log_stream_name,
                     'PhysicalResourceId': context.log_stream_name,
                     'StackId': event['StackId'],
                     'RequestId': event['RequestId'],
                     'LogicalResourceId': event['LogicalResourceId'],
                     'Data': json.loads("{}")}

    requests.put(event['ResponseURL'], data=json.dumps(response_body))

Specify the ARN of Lambda in the custom resource as follows.

AWSTemplateFormatVersion: '2010-09-09'

Resources:
  myBucketResource:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: test-bucket

  LambdaUsedToCleanUp:
     Type: Custom::cleanupbucket
     Properties:
       ServiceToken: arn:aws:lambda:us-west-2:XXXXXXXXXXXX:function:lambda_function_name
       BucketName: !Ref myBucketResource
profile picture
专家
已回答 1 年前
0
profile pictureAWS
专家
已回答 1 年前

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则