s3LambdaDataStore

Storing data in S3 with Lambda

Write serverless functions to store data in S3 buckets. ...

Storing data in an S3 bucket with Lambda functions is a useful way of managing data within a Serverless architecture.

This is my second post on how to use lambda functions with S3 buckets, here is the setup process for how to store data in s3 buckets with Lambda functions:

Step 1

Storing data in an S3 bucket with Lambda functions is a useful way of managing data within a Serverless architecture.
Create an S3 bucket (no specific configuration required), then create a lambda function using the below code (update it so its targetting your S3 bucket).

Step 2

Storing data in an S3 bucket with Lambda functions is a useful way of managing data within a Serverless architecture.
Be ensure to change the Lambda functions IAM role so that it has access to the ‘AmazonS3FullAccess’ permission.

Step 3

Storing data in an S3 bucket with Lambda functions is a useful way of managing data within a Serverless architecture.
Run the Lambda function by clicking the ‘Test’ button and see the data you’ve written within your function appear within the S3 Bucket you’ve created.

I’ve posted this scripts below (with comments) so you can now begin storing data in S3 with Lambda functions! I’ve also written a similar post to this on how to add authentication to S3 bucket with Lambda functions, you may find that useful too! Enjoy 😀

Lambda function

// import aws sdk
const AWS = require('aws-sdk');
// instantiate an instance of s3 from the aws sdk
const s3 = new AWS.S3();

// asynchronous function that executes when the lambda is run
exports.handler = async (event) => {
   // start try statement
    try {
        // run function to put data in S3
        await dataToS3({foo:"bar"});
        // console log a success
        console.log("succeeded");
    } catch (error) {
        // if the function failed, log the reason why
        throw new Error(`FAILED: dataToS3 lambda. ${error.message}`);
    }
}

// asynchronous function call to put data in s3
async function dataToS3(data) {
    // parameters required to access and store data in S3
    const params = {
        Bucket: 'jamesmillerblog-data-test',
        Key: 'helloWorld.json',
        Body: JSON.stringify(data),
    };
    // await result of a js promise that uses the specified parameters to store data in the S3 bucket
    await s3.putObject(params).promise();
};

Share this post