• Stars
    star
    213
  • Rank 185,410 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 8 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Serverless s3 local plugin.

serverless-s3-local

serverless npm version MIT licensed npm downloads

serverless-s3-local is a Serverless plugin to run S3 clone in local. This is aimed to accelerate development of AWS Lambda functions by local testing. I think it is good to collaborate with serverless-offline.

Installation

Use npm

npm install serverless-s3-local --save-dev

Use serverless plugin install

sls plugin install --name serverless-s3-local

Example

serverless.yaml

service: serverless-s3-local-example
provider:
  name: aws
  runtime: nodejs12.x
plugins:
  - serverless-s3-local
  - serverless-offline
custom:
# Uncomment only if you want to collaborate with serverless-plugin-additional-stacks
# additionalStacks:
#    permanent:
#      Resources:
#        S3BucketData:
#            Type: AWS::S3::Bucket
#            Properties:
#                BucketName: ${self:service}-data
  s3:
    host: localhost
    directory: /tmp
resources:
  Resources:
    NewResource:
      Type: AWS::S3::Bucket
      Properties:
        BucketName: local-bucket
functions:
  webhook:
    handler: handler.webhook
    events:
      - http:
        method: GET
        path: /
  s3hook:
    handler: handler.s3hook
    events:
      - s3: local-bucket
        event: s3:*

handler.js (AWS SDK v2)

const AWS = require("aws-sdk");

module.exports.webhook = (event, context, callback) => {
  const S3 = new AWS.S3({
    s3ForcePathStyle: true,
    accessKeyId: "S3RVER", // This specific key is required when working offline
    secretAccessKey: "S3RVER",
    endpoint: new AWS.Endpoint("http://localhost:4569"),
  });
  S3.putObject({
    Bucket: "local-bucket",
    Key: "1234",
    Body: new Buffer("abcd")
  }, () => callback(null, "ok"));
};

module.exports.s3hook = (event, context) => {
  console.log(JSON.stringify(event));
  console.log(JSON.stringify(context));
  console.log(JSON.stringify(process.env));
};

handler.js (AWS SDK v3)

const { S3Client, PutObjectCommand } = require("@aws-sdk/client-s3");

module.exports.webhook = (event, context, callback) => {
  const client = new S3Client({
    forcePathStyle: true,
    credentials: {
      accessKeyId: "S3RVER", // This specific key is required when working offline
      secretAccessKey: "S3RVER",
    },
    endpoint: "http://localhost:4569",
  });
  client
    .send(
      new PutObjectCommand({
        Bucket: "local-bucket",
        Key: "1234",
        Body: Buffer.from("abcd"),
      })
    )
    .then(() => callback(null, "ok"));
};

module.exports.s3hook = (event, context) => {
  console.log(JSON.stringify(event));
  console.log(JSON.stringify(context));
  console.log(JSON.stringify(process.env));
};

Configuration options

Configuration options can be defined in multiple ways. They will be parsed with the following priority:

  • custom.s3 in serverless.yml
  • custom.serverless-offline in serverless.yml
  • Default values (see table below)
Option Description Type Default value
address The host/IP to bind the S3 server to string 'localhost'
host The host where internal S3 calls are made. Should be the same as address string
port The port that S3 server will listen to number 4569
directory The location where the S3 files will be created. The directory must exist, it won't be created string './buckets'
accessKeyId The Access Key Id to authenticate requests string 'S3RVER'
secretAccessKey The Secret Access Key to authenticate requests string 'S3RVER'
cors Path to the S3 CORS configuration XML relative to the project root. See AWS docs string | Buffer
website Path to the S3 Website configuration XML relative to the project root. See AWS docs string | Buffer
noStart Set to true if you already have an S3rver instance running boolean false
allowMismatchedSignatures Prevent SignatureDoesNotMatch errors for all well-formed signatures boolean false
silent Suppress S3rver log messages boolean false
serviceEndpoint Override the AWS service root for subdomain-style access string amazonaws.com
httpsProtocol To enable HTTPS, specify directory (relative to your cwd, typically your project dir) for both cert.pem and key.pem files. string
vhostBuckets Disable vhost-style access for all buckets boolean true
buckets Extra bucket names will be created after starting S3 local string

Feature

  • Start local S3 server with specified root directory and port.
  • Create buckets at launching.
  • Support serverless-plugin-additional-stacks
  • Support serverless-webpack
  • Support serverless-plugin-existing-s3
  • Support S3 events.

Working with IaC tools

If your want to work with IaC tools such as terraform, you have to manage creating bucket process. In this case, please follow the below steps.

  1. Comment out configurations about S3 Bucket from resources section in serverless.yml.
#resources:
#  Resources:
#    NewResource:
#      Type: AWS::S3::Bucket
#      Properties:
#        BucketName: local-bucket
  1. Create bucket directory in s3rver working directory.
$ mkdir /tmp/local-bucket

Triggering AWS Events offline

This plugin will create a temporary directory to store mock S3 info. You must use the AWS cli to trigger events locally. First, using aws configure set up a new profile, i.e. aws configure --profile s3local. The default creds are

aws_access_key_id = S3RVER
aws_secret_access_key = S3RVER

You can now use this profile to trigger events. e.g. to trigger a put-object on a file at ~/tmp/userdata.csv in a local bucket run: aws --endpoint http://localhost:4569 s3 cp ~/tmp/data.csv s3://local-bucket/userdata.csv --profile s3local

You should see the event trigger in the serverless offline console: info: PUT /local-bucket/user-data.csv 200 16ms 0b and a new object with metadata will appear in your local bucket.

Enabling CORS

Create an .xml file with CORS configuration. See AWS docs

E.g. to enable CORS for GET requests:

<CORSConfiguration>
  <CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
    <MaxAgeSeconds>30000</MaxAgeSeconds>
    <ExposeHeader>x-amz-server-side-encryption</ExposeHeader>
  </CORSRule>
</CORSConfiguration>

Reference the file in your config:

custom:
  s3:
    host: localhost
    directory: /tmp
    cors: ./path/to/cors.xml

See also

License

This software is released under the MIT License, see LICENSE.

More Repositories

1

msgpack11

A tiny MessagePack library for C++11 (msgpack.org[C++11])
C++
120
star
2

poisson-blending-in-5lines

An implementation of Poisson Blending in 5 lines.
Python
17
star
3

teimpy

Python library for displaying image on terminal.
Python
8
star
4

pytorch-lightning-sam-callback

SAM with pytorch-lightning's Callback API
Python
6
star
5

serverless-plugin-export-endpoints

Export lambda endpoints as json
JavaScript
6
star
6

resaspy

python for RESAS API
Python
6
star
7

paaaaath

useful path like object
Python
5
star
8

vanilla-roll

array-api based simple volume renderer
Python
4
star
9

lab

my laboratory
Jupyter Notebook
4
star
10

mameMalloc

Plain header only implementation of malloc/free.
C
3
star
11

halide_anaconda3

Dockerfile for halide and anaconda3
Shell
2
star
12

alfort

Elm-like interactive application framework for Python
Python
2
star
13

docker-ise-webpack-vnc

ISE Webpack in Docker image
Dockerfile
2
star
14

kkt

A tool for kaggle kernel management.
Python
1
star
15

dcmagick

DICOM Image manipulation tool
Python
1
star
16

mameBitmap

header only library for bitmap images
C++
1
star
17

react-8bit-paint

8bit paint app with React
TypeScript
1
star
18

LogcatVisor

This project aims to develop a software for overlaying logcat output on display.
Java
1
star
19

HighGUI3DCG

C++による簡単実習 3次元CG入門 第2版 のサンプルコードのHighGUIによるバックエンド
C++
1
star
20

mameJpeg

Header only plain jpeg codec
C
1
star
21

countrymaam

Plain ann-search implementation with Go
Go
1
star
22

kmeaaaaans

Simple kmeans clustering algorithm implementation with pure Go
Go
1
star
23

ziglings

Zig
1
star