Invoking Lambda Functions in a Different Account via S3 Upload

By Chris Diggs | April 28, 2018

In a recent Blog post, we talked about giving Lambda functions access to resources in another account. In this Blog entry, we’ll investigate how to invoke a Lambda Function in another account by using AWS’ S3 event notifications. We assume you already have a Lambda function in a different account that you want to invoke. We’ll identify the necessary steps to trigger the function by uploading files to an S3 bucket.



  1. Create an S3 bucket (if not already created)

aws s3api create-bucket \

--bucket <my-bucket> \

--region us-east-1

  • Remember bucket names are unique per region

  • Make sure to create the bucket in same region as your Lambda function!



  1. Add a permission to the Lambda function that allows the function to be triggered from the S3 bucket

aws lambda add-permission \

--region us-east-1 \

--function-name <lambda-function-name> \

--statement-id s3-invoke \

--principal s3.amazonaws.com \

--action lambda:InvokeFunction \

--source-arn arn:aws:s3:::<my-bucket> \

--source-account <s3-account-number>



  1. Add an event notification to the s3 bucket

  • s3-event.json

{

"QueueConfigurations": [

{

"QueueArn": "<lambda-function-arn>",

"Events": [

"s3:ObjectCreated:Put"

],

"Filter": {

"Key": {

"FilterRules": {

"Name": "suffix",

"Value": ".txt"

}

}

}

}

]

}

  • Notice, the above statement implies we’ll only invoke the Lambda function if the file uploaded has a ‘.txt’ extension.

  • It’s possible to add multiple prefix/suffix filter rules, to fit your particular needs.

  • You can also add multiple event notifications to the same bucket.

aws s3api put-bucket-notification-configuration \

--bucket <my-bucket> \

--notification-configuration file://s3-event.json \

--region us-east-1



  1. Test! Upload a file with a ‘.txt’ extension to your S3 bucket and verify your Lambda function gets invoked.



Note: You will get the following error when viewing the Lambda Function from the console. However, the functionality of triggering the Lambda function from an S3 upload in a different account should still work.



comments powered by Disqus