Skip to content

SAM local invoke with event don't working

0

Hi,

I'm developing a Lambda Function to be triggered by a file uploaded to S3. This is my SAM File

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Simple lambda function triggered by a file uploaded to a S3 container

Resources:

  S3Storage:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: 
        Fn::Sub: "${AWS::StackName}-bucket"

  ListenerFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/
      Handler: app.lambda_handler
      Runtime: python3.11
      FunctionName: s3-listener
      Events:
        S3Event:
          Type: S3
          Properties:
            Bucket: 
              Ref: S3Storage
            Events: 
              - s3:ObjectCreated:*
      Policies: 
        - S3ReadPolicy:
            BucketName: 
              Fn::Sub: "${AWS::StackName}-bucket"

To test locally, I followed the instructions

  1. Using sam local invoke to build a local docker image.
  2. I generated test event with sam generate-event. This is my event generated. The bucket and file name (object key) are real
{
  "Records": [
    {
      "eventVersion": "2.0",
      "eventSource": "aws:s3",
      "awsRegion": "us-east-1",
      "eventTime": "1970-01-01T00:00:00.000Z",
      "eventName": "ObjectCreated:Put",
      "userIdentity": {
        "principalId": "EXAMPLE"
      },
      "requestParameters": {
        "sourceIPAddress": "127.0.0.1"
      },
      "responseElements": {
        "x-amz-request-id": "EXAMPLE123456789",
        "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH"
      },
      "s3": {
        "s3SchemaVersion": "1.0",
        "configurationId": "testConfigRule",
        "bucket": {
          "name": "s3-triggers-lambda-bucket",
          "ownerIdentity": {
            "principalId": "EXAMPLE"
          },
          "arn": "arn:aws:s3:::s3-triggers-lambda-bucket"
        },
        "object": {
          "key": "users.csv",
          "size": 1024,
          "eTag": "0123456789abcdef0123456789abcdef",
          "sequencer": "0A1B2C3D4E5F678901"
        }
      }
    }
  ]
}

When running sam local invoke I realized the the Lambda is called but failed since it expects and event.

Enter image description here

But when I run sam local invoke --event .\events\s3.json ListenerFunction the Lambda crashes.

Enter image description here

I saw something similar in this rePost, with no response

This is my Lambda, its quite simple:

import logging
import boto3
from urllib.parse import unquote_plus

logger = logging.getLogger()
logger.setLevel(logging.INFO)

logger.info('Loading function')

s3 = boto3.client('s3')

def lambda_handler(event, context):

    # Get the object from the event and show its content type
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')

    try:
        response = s3.get_object(Bucket=bucket, Key=key)
        logger.info("CONTENT TYPE: " + response['ContentType'])
        return response['ContentType']
    except Exception as e:
        logger.error(e)
        logger.error('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
        raise e

Can somebody give a hand on this?

Regards

Jona

1 Answer
1
Accepted Answer

Thanks to the clues given here, I realized that sam local generate-event s3 put --bucket s3-triggers-lambda-bucket > .\events\s3.json outputed the file as UTF-16. I changed to UTF-8 using VS Code and everything works like a charm.

Enter image description here

Regards

answered 2 years ago
EXPERT
reviewed 2 years ago
EXPERT
reviewed 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.