Setting Up an S3 Trigger for an AWS Lambda Function in the AWS Clouformation

To set up an AWS Lambda function, an Amazon S3 bucket, and an S3 trigger for the function using AWS CloudFormation, you can use the AWS::Lambda::Function, AWS::S3::Bucket, and AWS::Lambda::EventSourceMapping resources. Here is an example of how you might use these resources in a CloudFormation template:

AWSTemplateFormatVersion: "2010-09-09"
Description: "Create Lambda S3 triggger"

Parameters:
  MyBucketName:
    Description: S3 Bucket Name
    Type: String
    Default: abhaysingh091290

Resources:
  MyIAMRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - sts:AssumeRole
      Policies:
        - PolicyName: MyPolicy
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - s3:ListBucket
                Resource: arn:aws:s3:::${MyBucketName}
  LambdaPermission:
    Type: AWS::Lambda::Permission
    Properties:
      Action: 'lambda:InvokeFunction'
      FunctionName: !Ref MyFunction
      Principal: s3.amazonaws.com
      SourceArn: !Sub 'arn:aws:s3:::${MyBucketName}'
      SourceAccount: !Ref AWS::AccountId
  MyFunction:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        ZipFile: |
          def handler(event, context):
            return "Hello, World!"
      Handler: index.handler
      Role: !GetAtt MyIAMRole.Arn
      Runtime: python3.8
      Timeout: 30
  MyBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Ref MyBucketName
      NotificationConfiguration:
        LambdaConfigurations:
          - Event: s3:ObjectCreated:*
            Function: !GetAtt MyFunction.Arn
            Filter:
              S3Key:
                Rules:
                  - Name: Suffix
                    Value: ".txt"
                  - Name: Prefix
                    Value: "test-"
ALSO READ  How to create AWS QuickSight Data Source with AWS CloudFormation

Abhay Singh

I'm Abhay Singh, an Architect with 9 Years of It experience. AWS Certified Solutions Architect.

More Reading

Post navigation

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *