haju
haju

Reputation: 241

How to add a object notication event trigger to a serveless lamda in cloudformation?

I am creating a lambda function (serverless) via cloudformation , see template below . in my aws account there are s3 buckets which were created manually and i can't add or change them. so can i add , s3 object notification trigger in my lambda? if so, i want to trigger this event, only for files under certain prefix/folder and for certain extensions . how can i achieve this ? do i need s3 bucket name or arn for this ?

AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31

Resources:
  MyLambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      Role: !GetAtt LambdaRole.Arn
      Runtime: python3.9
      Handler: index.lambda_handler
      code:
      ....
      Tags:
        - Key: Lambda
          Value: MyLambdaFunction
      ...
  LambdaRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - ec2.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Path: /
      Policies:
        - PolicyName: policy..
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action: 's3:*'
                Resource: '*'

Upvotes: 0

Views: 30

Answers (1)

Ayush Shah
Ayush Shah

Reputation: 158

You can set trigger but you need to use AWS::Serverless::Function instead of AWS::Lambda::Function.

In AWS::Lambda::Function it is not possible.

and configure events into the AWS::Serverless::Function properties

Events:
  S3Event:
    Type: S3
    Properties:
      Bucket:
        Ref: ImagesBucket     
      Events: s3:ObjectCreated:*
      Filter:
        S3Key:
          Rules:
          - Name: prefix      # or "suffix"
            Value: value      # The value to search for in the S3 object key names

You can refer this link

If you want to know what is the difference between lambda function and serverless function please refer this

You can import your existing s3 bucket to cloudformation as well. aws provide resource import option as well.

Upvotes: 1

Related Questions