How to Use AWS CLI to Configure an S3 Bucket to Trigger a Lambda Function

Hemanta Sundaray

Published December 3, 2023


Follow the steps below to configure an Amazon S3 bucket to trigger an AWS Lambda function using AWS CLI.

Step 1: Grant the Lambda Function Permission to be Invoked by S3

Run the following command that adds permission to the Lambda function, allowing it to be invoked by S3. This is crucial because it establishes a trust relationship between the S3 bucket and the Lambda function.

aws lambda add-permission \
--function-name <FUNCTION_NAME> \
--principal s3.amazonaws.com \
--statement-id s3invoke \
--action "lambda:InvokeFunction" \
--source-arn <SOURCE_BUCKET_ARN> \
--source-account <AWS_ACCOUNT_ID>

Replace <SOURCE_BUCKET_ARN> with the ARN of the S3 bucket that will trigger the Lambda function. Note that S3 bucket ARNs follow a standard format:

arn:aws:s3:::<BUCKET_NAME>

So knowing the bucket name is sufficent to construct the ARN manually.

Step 2: Configure S3 Event Notification to Trigger the Lambda Function

Once the permission is in place, you can then configure the S3 bucket to send an event to your Lambda function when the specified action (like object creation) occurs. You use the put-bucket-notification-configuration command for this:

aws s3api put-bucket-notification-configuration \
--bucket <BUCKET-NAME> \
--notification-configuration '{
    "LambdaFunctionConfigurations": [
        {
            "LambdaFunctionArn": "arn:aws:lambda:<AWS_REGION>:<AWS_ACCOUNT_ID>:function:<FUNCTION_NAME>",
            "Events": ["<EVENT_NAME>"]
        }
    ]
}'

In this command, replace <EVENT_NAME> with the S3 bucket event for which you want to trigger the Lambda function. For example, s3:ObjectCreated:* triggers the function for all object creation events.

By following this sequence, you first ensure that the Lambda function is authorized to receive events from S3, and then you set up the S3 bucket to send those events.