Skip to main content

Amazon S3

Trigger AWS Lambda from an S3 event

S3 to AWS Lambda diagram

In this pattern, we will walk through how to trigger AWS Lambda from S3 object events.

Packages Required

install

dotnet add package Amazon.Lambda.S3Events

Function Code

The S3 to Lambda integration is what is known as an asynchronous invoke. Events are forwarded to the Lambda service and processed asynchronously, meaning the caller can continue doing other work.

The S3Event object contains an array of S3EventNotification objects. S3 Events are passed to Lambda in batches.

The S3EventNotification object contains both an Bucket and Object property. It's important to note that the Object.Key property will always be URL encoded. However, if you need to make a call to the S3 API then you need the URL decoded key string. That's caught me out many times 😢

Function.cs

public class Function
{
public async Task Handler(S3Event evt, ILambdaContext context)
{
try
{
if (evt.Records.Count <= 0)
{
context.Logger.LogLine("Empty S3 Event received");
return;
}
foreach (var s3Object in evt.Records)
{
var bucket = evt.Records[0].S3.Bucket.Name;
// The object key will always be URL encoded.
// However, the API call to S3 requires a URL decoded string
var key = HttpUtility.UrlDecode(evt.Records[0].S3.Object.Key);
context.Logger.LogLine($"Request is for {bucket} and {key}");
var objectResult = await _s3Client.GetObjectAsync(bucket, key);
context.Logger.LogLine($"Key is {objectResult.Key}");
}
}
catch (Exception e)
{
context.Logger.LogLine($"Error processing request - {e.Message}");
}
}
}

Best Practices

  • Remember to URL decode your object key if you need to do any further work with the S3 API.