How to write to S3 bucket from Lambda function

AWS SAM template to create a Lambda function and an S3 bucket. Cloudformation world


May 12, 2021
featured image

Overview

AWS resources we need

  • Lambda Function
  • S3 Bucket
  • Lambda Role
  • Bucket Policy

The Lambda function

      
const AWS = require("aws-sdk");
const s3 = new AWS.S3({
    region: "us-east-1",
});
let response;

exports.lambdaHandler = async (event, context) => {
    try {
        console.log(event);
        const params = {
            Bucket: process.env.MY_BUCKET,
            Key: 'test-file.txt',
            Body: "test content"
        }
        console.log('writing to s3', params);
        const result =  await s3.putObject(params).promise();
        console.log(result);

        response = {
            'statusCode': 200,
        }
    } catch (err) {
        console.log(err);
        return err;
    }

    return response
};

      

The SAM template

      
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  Sample SAM Template for Lambda and S3
Parameters:
  Environment:
    Type: String
    Description: Environment name. Example, staging
Resources:
  MyLambda:
    Type: AWS::Serverless::Function
    DependsOn:
      - "MyBucket"
    Properties:
      CodeUri: hello-world/
      Handler: app.lambdaHandler
      Runtime: nodejs12.x
      Environment:
        Variables:
          MY_BUCKET:
            Ref: "MyBucket"
      Role:
        Fn::GetAtt:
          - "MyLambdaRole"
          - "Arn"
    Tags:
      Name: !Sub "${Environment}-my-test-lambda"

  MyBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub "${Environment}-my-test-bucket"

  MyBucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      PolicyDocument:
        Id: BucketPolicy
        Version: 2012-10-17
        Statement:
          - Sid: AccessAll
            Action: s3:*
            Effect: Allow
            # Beware: this makes your bucket public!
            Principal: "*"
            Resource: !Join
              - ''
              - - 'arn:aws:s3:::'
                - !Ref MyBucket
                - /*
      Bucket: !Ref MyBucket

  MyLambdaRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Effect: Allow
            Action: "sts:AssumeRole"
            Principal:
              Service:
                - "lambda.amazonaws.com"
        Version: "2012-10-17"
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Policies:
        - PolicyName: MyLambdaPolicy
          PolicyDocument:
            Statement:
              - Effect: Allow
                Action: "s3:*"
                Resource:
                  - Fn::GetAtt:
                      - "MyBucket"
                      - "Arn"
            Version: "2012-10-17"

      

Deploy

Build our lambda and template. This will check also the syntax of your template
      
sam build
      
Only for the first time run and follow the steps
      
sam deploy --guided
      
The second time and so on you can execute
      
sam deploy --no-confirm-changeset
      

Resources

Photo by Samur Isma on Unsplash


aws cloudformation lambda s3