3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LambdaでS3の特定バケットにjsonを作成・編集したい

Last updated at Posted at 2019-08-29

なんか情報少なくね

って言うわけで忘備録代わりに投稿

前提

  • Lambda(Node.js)
  • S3のバケット

やり方

JSONを作成し、S3に保存

index.js
const aws = require('aws-sdk');
const s3 = new aws.S3({ apiVersion: '2006-03-01' });
const bucket = BUCKET_NAME; //バケットの名前
exports.handler = async (event, context) => {
    const key = "hogehoge.json"//書き込みたいjsonのkey
    const content = CONTENT; //これにS3で保存したいJSONの内容を入れる
    const params = {
        Bucket: bucket,
        Key: key,
        Body: JSON.stringify(content)
    };
    await s3.putObject(params).promise();
}

S3からLambdaでJSONを読み込む

index.js
const aws = require('aws-sdk');
const s3 = new aws.S3({ apiVersion: '2006-03-01' });
const bucket = BUCKET_NAME; //バケットの名前
exports.handler = async (event, context) => {
    const key = "hogehoge.json";//読み込みたいjsonの場所を指定
    // ルートにないファイルはcons ket = "file/hogehoge.json"みたい指定
    const params = {
        Bucket: bucket,
        Key: key
    };
    let content = await s3.getObject(params).promise();
    content = JSON.parse(content.Body.toString());
}

適当にtry-catchを使ったりしてエラーハンドリングした方が良いが、最低でもこれで読み込める。
この2つで読み込んで編集する事もできるので、s3.getObjectとs3.putObjectは覚えとくと便利。

余談

keyにfile/../hogehoge.jsonみたいな普通だとルートが参照されてしまう様なものを渡してもルートは参照されない。
これはAmazon S3における「フォルダ」という幻想をぶち壊し、その実体を明らかにするの様に、S3にはフォルダという概念がなく「..」というkeyそのものがファイル名として解釈されるためである。
しかし、さらにセキュリティを高め事故を防ぎたいならIAMでリソースをarn:aws:s3:::BUCKET_NAME/FILE/*.jsonの様に指定する事でさらに操作を制限できるため、よほどの理由がないなら設定しとくべき。スクリーンショット 2019-08-29 18.25.19.png

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?