'How to use a s3 trigger to invoke a lambda function for a specific folder in s3 bucket
I created a lambda function using blueprint- s3-get-object-python. I want to the get the function invoked only when I upload a file into the certain folder of the s3 bucket I created. I tried adding prefix with -"foldername/" while creating the trigger, but it is not work.
Below is the code which my lambda function contains. I know the code isnt the matter here.
console.log('Loading function');
const aws = require('aws-sdk');
const s3 = new aws.S3({ apiVersion: '2006-03-01' });
exports.handler = async (event, context) => {
//console.log('Received event:', JSON.stringify(event, null, 2));
// Get the object from the event and show its content type
const bucket = event.Records[0].s3.bucket.name;
const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
const params = {
Bucket: bucket,
Key: key,
};
try {
const { ContentType } = await s3.getObject(params).promise();
console.log('CONTENT TYPE:', ContentType);
return ContentType;
} catch (err) {
console.log(err);
const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
console.log(message);
throw new Error(message);
}
};
Solution 1:[1]
You are probably missing the proper Resource-based policy for your Lambda. That is something you configure in your Lambdas configuration.
It is a configuration granting the S3 service permission to invoke your Lambda function. Without this permission, the S3 service won't be able to invoke your Lambda.
If you use the AWS CLI you could do it like this:
aws \
lambda \
add-permission \
--function-name <your-function-name> \
--action lambda:InvokeFunction \
--statement-id allow-s3-invoke \
--principal s3.amazonaws.com \
--source-arn <your-bucket-arn> \
--source-account <your-account-id>
You can find the relevant documentation here:
https://docs.aws.amazon.com/lambda/latest/dg/access-control-resource-based.html
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jens |
