pymat
pymat

Reputation: 1192

CloudFormation stack not triggering AWS Lambda from an S3 upload

I'm using CloudFormation to deploy a stack, whereby a file upload to an existing S3 bucket and object triggers a Lambda function. The stack deploys without errors, however in the UI the connection between the S3 and Lambda resource is not shown, therefore a triggering cannot take place.

I've seen quite a few posts already regarding this topic, all with different flavours to the setup I require. In addition, I have seen the !ImportValue to use, as seen here, however the parameter Bucket is not recognised.

As mentioned already, the S3 bucket and object exist already, so I need to somehow reference an already existing resource in my template.yml. The current status is:

      MyTrigger:
        Type: AWS::Serverless::Function
        Properties:
          FunctionName: !Ref LambdaModuleName
          CodeUri: src/my_module
          Handler: app.lambda_handler
          Runtime: python3.9
          MemorySize: 7500
          Timeout: 600
          ReservedConcurrentExecutions: 1
    
          Policies:
            - AWSLambdaExecute
            - AWSLambdaVPCAccessExecutionRole
            - Statement:
                - Sid: StagingS3DeleteCreate
                  Effect: Allow
                  Action:
                    - s3:DeleteObject*
                    - s3:PutObject*
                  Resource:
                    - arn:aws:s3:::bucket1/folder1/folder2/*
                - Sid: StagingS3List
                  Effect: Allow
                  Action:
                    - s3:List*
                  Resource:
                    - arn:aws:s3:::*
    
      # Permissions
      AllowS3ToCallLambdaPermission:
        Type: AWS::Lambda::Permission
        Properties:
          Action: 'lambda:InvokeFunction'
          FunctionName: !Ref MyTrigger
          Principal: s3.amazonaws.com
          SourceArn: arn:aws:s3:::bucket1/folder1/folder2/

My question is how can deploy a stack and reference this existing bucket and object, so that it triggers the Lambda upon a file upload?

UPDATE

Added:

  StagingBucket:
    Type: "AWS::S3::Bucket"
    DeletionPolicy: Retain
    Properties:
      BucketName: !Ref S3SourceBucket

where:

  S3SourceBucket:
    Type: String
    Default: "mybucket"

Upvotes: 0

Views: 744

Answers (1)

fedonev
fedonev

Reputation: 25799

You have set the IAM permissions, but not actually enabled the notifications.

The S3 Bucket Notification Configuration is a property of the S3 bucket itself. You won't be able to add it to a bucket that is not part of this stack. You can fix this by importing the existing AWS::S3::Bucket resource so that it's part of, and managed by, the stack.

Once the existing bucket has been imported into the stack, you can set its LambdaConfiguration, which tells S3 which Lambda to invoke and when.

Upvotes: 1

Related Questions