KVISH KVISH - 1 month ago 31
Node.js Question

AWS Lambda function write to S3

I have a Node 4.3 Lambda function in AWS. I want to be able to write a text file to S3 and have read many tutorials about how to integrate with S3. However, all of them are about how to call Lambda functions after writing to S3 like below:

http://docs.aws.amazon.com/lambda/latest/dg/with-s3.html

How can I create a text file in S3 from Lambda using node? Is this possible? Amazons documentation doesn't seem to cover it.

Answer

Yes it is absolutely possible!

function putObjectToS3(bucket, key, data){
    var s3 = new AWS.S3();
        var params = {
            Bucket : bucket,
            Key : key,
            Body : data
        }
        s3.putObject(params, function(err, data) {
          if (err) console.log(err, err.stack); // an error occurred
          else     console.log(data);           // successful response
        });
}

Make sure that you give your Lambda function the required write permissions to the target s3 bucket / key path by selecting or updating the IAM Role your lambda executes under.

IAM Statement to add:

{
    "Sid": "Stmt1468366974000",
    "Effect": "Allow",
    "Action": "s3:*",
    "Resource": [
        "arn:aws:s3:::my-bucket-name-goes-here/optional-path-before-allow/*"
    ]
}

Further reading:

AWS JavaScript SDK: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html

The specific "Put Object" details: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObject-property