CloudFormation을 사용하여 기존 S3 버킷에서 Lambda에 대한 Amazon S3 알림 구성을 만들려면 어떻게 해야 하나요?
기존 Amazon Simple Storage Service(Amazon S3) 버킷을 사용하여 AWS Lambda 함수에 대한 Amazon S3 알림 구성을 생성하려고 합니다. AWS CloudFormation을 사용하여 이 작업을 수행하고 싶습니다.
간략한 설명
Amazon S3 알림 구성을 생성하기 위해 CloudFormation을 사용하여 새 S3 버킷을 생성할 수 있습니다. 그런 다음 NotificationConfiguration 속성을 사용해 해당 버킷에 알림 구성을 추가하세요. 또는 기존 S3 버킷에 수동으로 알림 구성을 추가하세요.
다음 단계는 CloudFormation으로 기존 S3 버킷에 알림 구성을 추가하는 방법을 보여줍니다. Python 3.9에서 만든 Lambda 지원 사용자 지정 리소스를 사용하여 수행할 수 있습니다. 사용자 지정 리소스가 Lambda 함수를 시작하면 함수가 PutBucketNotification API를 시작하여 S3 버킷에 알림 구성을 추가합니다.
참고: AWS Command Line Interface(AWS CLI) 명령을 실행할 때 오류가 발생할 경우 AWS CLI의 최신 버전을 사용하고 있는지 확인하세요.
해결 방법
중요: 다음 단계는 기존 알림 구성이 없는 S3 버킷의 Amazon S3 알림 구성에만 적용됩니다. S3 버킷에 기존 또는 수동으로 생성한 알림 구성이 이미 있는 경우, 다음 단계를 수행하면 해당 구성이 재정의됩니다. 스택을 삭제하면 모든 알림이 제거됩니다. 솔루션이 작동하는 것으로 보이는 경우, 사용 사례에 대한 최적이 아닌 차선 구성이 있을 수 있습니다. 모범 사례는 프로덕션 환경에 배포하기 전에 테스트 S3 버킷에서 솔루션을 테스트하는 것입니다.
1. 다음 코드를 포함하는 LambdaS3.template이라는 CloudFormation 템플릿을 생성합니다.
중요: 다음 예제에서는 S3Notification****LambdaFunction 리소스에 S3 알림 구성을 추가합니다. CustomResourceLambdaFunction Lambda 함수를 사용하여 S3NotificationLambdaFunction에 대한 S3 알림 구성을 추가합니다. CustomResourceLambdaFunction 리소스의 코드를 요구 사항에 맞게 수정할 수 있습니다.
AWSTemplateFormatVersion: 2010-09-09 Description: >- Sample template to illustrate use of existing S3 bucket as an event source for a Lambda function Parameters: NotificationBucket: Type: String Description: S3 bucket that's used for the Lambda event notification Resources: S3NotificationLambdaFunction: Type: 'AWS::Lambda::Function' Properties: Code: ZipFile: !Join - |+ - - import json - 'def lambda_handler(event,context):' - ' return ''Welcome... This is a test Lambda Function''' Handler: index.lambda_handler Role: !GetAtt LambdaIAMRole.Arn Runtime: python3.9 Timeout: 5 LambdaInvokePermission: Type: 'AWS::Lambda::Permission' Properties: FunctionName: !GetAtt S3NotificationLambdaFunction.Arn Action: 'lambda:InvokeFunction' Principal: s3.amazonaws.com SourceAccount: !Ref 'AWS::AccountId' SourceArn: !Sub 'arn:aws:s3:::${NotificationBucket}' LambdaIAMRole: Type: 'AWS::IAM::Role' Properties: AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: Service: - lambda.amazonaws.com Action: - 'sts:AssumeRole' Path: / Policies: - PolicyName: root PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - 's3:GetBucketNotification' - 's3:PutBucketNotification' Resource: !Sub 'arn:aws:s3:::${NotificationBucket}' - Effect: Allow Action: - 'logs:CreateLogGroup' - 'logs:CreateLogStream' - 'logs:PutLogEvents' Resource: 'arn:aws:logs:*:*:*' CustomResourceLambdaFunction: Type: 'AWS::Lambda::Function' Properties: Handler: index.lambda_handler Role: !GetAtt LambdaIAMRole.Arn Code: ZipFile: | from __future__ import print_function import json import boto3 import cfnresponse SUCCESS = "SUCCESS" FAILED = "FAILED" print('Loading function') s3 = boto3.resource('s3') def lambda_handler(event, context): print("Received event: " + json.dumps(event, indent=2)) responseData={} try: if event['RequestType'] == 'Delete': print("Request Type:",event['RequestType']) Bucket=event['ResourceProperties']['Bucket'] delete_notification(Bucket) print("Sending response to custom resource after Delete") elif event['RequestType'] == 'Create' or event['RequestType'] == 'Update': print("Request Type:",event['RequestType']) LambdaArn=event['ResourceProperties']['LambdaArn'] Bucket=event['ResourceProperties']['Bucket'] add_notification(LambdaArn, Bucket) responseData={'Bucket':Bucket} print("Sending response to custom resource") responseStatus = 'SUCCESS' except Exception as e: print('Failed to process:', e) responseStatus = 'FAILED' responseData = {'Failure': 'Something bad happened.'} cfnresponse.send(event, context, responseStatus, responseData) def add_notification(LambdaArn, Bucket): bucket_notification = s3.BucketNotification(Bucket) response = bucket_notification.put( NotificationConfiguration={ 'LambdaFunctionConfigurations': [ { 'LambdaFunctionArn': LambdaArn, 'Events': [ 's3:ObjectCreated:*' ] } ] } ) print("Put request completed....") def delete_notification(Bucket): bucket_notification = s3.BucketNotification(Bucket) response = bucket_notification.put( NotificationConfiguration={} ) print("Delete request completed....") Runtime: python3.9 Timeout: 50 LambdaTrigger: Type: 'Custom::LambdaTrigger' DependsOn: LambdaInvokePermission Properties: ServiceToken: !GetAtt CustomResourceLambdaFunction.Arn LambdaArn: !GetAtt S3NotificationLambdaFunction.Arn Bucket: !Ref NotificationBucket
2. LambdaS3.template 파일을 사용하여 CloudFormation 스택을 시작하려면, CloudFormation 콘솔 또는 다음 AWS CLI 명령을 사용하세요.
aws cloudformation create-stack --stack-name lambda-s3-notification --template-body file://LambdaS3.template --parameters ParameterKey=NotificationBucket,ParameterValue=existing-bucket-for-lambda-notification --capabilities CAPABILITY_NAMED_IAM --region us-east-1
중요: CloudFormation 스택을 시작할 때 S3 버킷을 거쳐야 합니다. 예: existing-bucket-for-lambda-notification
스택에서 Lambda 함수 및 Amazon S3에 대한 Lambda 권한이 생성됩니다. 즉, 스택이 S3 버킷에 필요한 알림 구성을 추가했으므로 이제 S3 버킷을 Lambda 알림에 사용할 수 있습니다.
관련 콘텐츠
- 질문됨 3년 전lg...
- 질문됨 3달 전lg...
- 질문됨 6년 전lg...
- 질문됨 24일 전lg...
- AWS 공식업데이트됨 10달 전