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 年前

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南