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
전문가
답변함 일 년 전
0
profile pictureAWS
전문가
답변함 일 년 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠