S3 upload object tagging in AWS Lambda

Posted by Lukas Hajdu on Tue, Jan 14, 2020

AWS SAM allows you to choose from ready-made policy templates to scope the permissions of Lambda functions. You might experience an “Access Denied” error when you play around with the AWS SDK. It’s always a good idea to review the permissions of your application and required permissions to execute the function.

The list of policy templates can be found in the serverless policy template table.

If you are using, for example, the S3CrudPolicy to put objects into a bucket, you might experience an error similar to the one below while you are putting objects into the bucket with a custom tagging.

1ERROR	Invoke Error 	{"errorType":"AccessDenied","errorMessage":"Access Denied","code":"AccessDenied","message":"Access Denied","region":null,"time":"2020-01-14T22:40:58.757Z","requestId": "...", ...}

After reviewing the S3CrudPolicy you will realise that the object tagging permission is not part of the list of allowed actions. To tag the uploaded object, the access policy needs to have the s3:PutObjectTagging permissions which is part of the S3FullAccessPolicy.

This quick permission fix will enable you to tag uploaded objects.

Example lambda function

Let’s create an example lambda function which will create a new text file, tag the file and put it into the S3 bucket.

index.js

 1const aws = require('aws-sdk');
 2const s3 = new aws.S3();
 3
 4exports.handler = async (event) => {
 5
 6    var buffer = Buffer.from("Hello lambda function!", "utf-8");
 7    var params = {
 8        Body: buffer, 
 9        Bucket: "MyBucket", 
10        Key: "hello-lambda.txt",
11        Tagging: "myTag1=hello&myTag2=lambda"
12    };
13    
14    try {
15        const { Body } = await s3.putObject(params).promise();
16
17        return Promise.resolve(Body);
18    } catch(err) {
19        return Promise.reject(err);
20    }
21};

The belonging template file with the correct S3 bucket policy will look like this:

template.yaml

 1...
 2
 3Resources:
 4  MyFunction:
 5    Type: AWS::Serverless::Function
 6    Properties:
 7      CodeUri: ./src
 8      Handler: index.handler
 9      Runtime: nodejs10.x
10      Description: My lambda function
11      Policies: 
12        - S3FullAccessPolicy:
13            BucketName: MyBucket
14
15...

After running this lambda function you should see a new file hello-lambda.txt in the MyBucket. When you review properties of the uploaded file you should see your created tags under the Tags property:

S3 Object tagging
S3 Object tagging



comments powered by Disqus