LoginSignup
19

More than 5 years have passed since last update.

LambdaでS3間のファイルコピー

Last updated at Posted at 2016-09-13

2016/09現在の情報です。

Lambda関数を作るまで

AWSログイン後

1) Lambda
2) 「Create a Lambda function」
3) 「s3-get-object」を選択

Configure triggers

1) 以下を入力

項目   内容
Bucket コピー元バケット
Event type Put
Prefix コピー元ディレクトリなど
Suffix コピー元ファイルの拡張子など
Enable trigger チェック

2) 「Next」

Configure function

1) 以下を入力

項目   内容
Name Lambda function名(適当に)
Description 適当に
Runtime Node.js 4.3(初期値)

Lambda function code

デフォルト:getObjectのみ

'use strict';

console.log('Loading function');

const aws = require('aws-sdk');

const s3 = new aws.S3({ apiVersion: '2006-03-01' });


exports.handler = (event, context, callback) => {
    //console.log('Received event:', JSON.stringify(event, null, 2));

    // Get the object from the event and show its content type
    const bucket = event.Records[0].s3.bucket.name;
    const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
    const params = {
        Bucket: bucket,
        Key: key,
    };
    s3.getObject(params, (err, data) => {
        if (err) {
            console.log(err);
            const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
            console.log(message);
            callback(message);
        } else {
            console.log('CONTENT TYPE:', data.ContentType);
            callback(null, data.ContentType);
        }
    });
};

→putObjectを追加

'use strict';

console.log('Loading function');

const aws = require('aws-sdk');

const s3 = new aws.S3({ apiVersion: '2006-03-01' });


exports.handler = (event, context, callback) => {
    //console.log('Received event:', JSON.stringify(event, null, 2));

    // Get the object from the event and show its content type
    const bucket = event.Records[0].s3.bucket.name;
    const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
    const params = {
        Bucket: bucket,
        Key: key,
    };
    s3.getObject(params, (err, data) => {
        if (err) {
            console.log(err);
            const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
            console.log(message);
            callback(message);
        } else {
            const putBucket = "コピー先バケット";
            const putKey = "コピー先ファイルパス";
            const contentType = "Content-Typeヘッダ";
            var put = {Bucket: putBucket, Key: putKey, Body: data.Body, ContentType: contentType};
            s3.putObject(put, function(err, data) {
                if (err) {
                    console.error(err);
                    const message = `Error putting object ${putKey} from bucket ${putBucket}.`;
                    console.error(message);
                    callback(message);
                } else {
                    callback(null);
                }
            });
        }
    });
};

Lambda function handler and role

1) 以下を入力

項目   内容
Handler index.handler(初期値)
Role 「Create new role from template(s)」(初期値)
Role name 適当に
Policy templates 「S3 object read-only permissions」(初期値)

Advanced settings

1) 以下を入力

項目   内容
Memory (MB) 128(初期値)
Timeout 0 min 3 sec(初期値)
VPC No VPC

※Memory、Timeoutは、初期値で実行してみて、メモリ不足やタイムアウトが起こったら増やす

2) 「Next」

Review

1) 「Create function」

権限を追加する

AWSログイン後

1) Identity & Access Management
2) ロール
3) 「Lambda function handler and role」で作成したRole nameで検索

アクセス許可

1) 「AWSLambdaS3ExecutionRole・・・」で始まるポリシー名をクリック

ポリシードキュメント

1) 「編集」
2)
デフォルト

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetObject"
            ],
            "Resource": "arn:aws:s3:::*"
        }
    ]
}

→PutObjectを追加

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": "arn:aws:s3:::*"
        }
    ]
}

3) 「保存」

動作確認

AWSログイン後

1) S3
2) コピー元バケットをクリック
3) ファイルをアップロード
 ※「Configure triggers」にてPrefix、Suffixを設定した場合は、それに合わせたディレクトリ、拡張子とする
4) コピー先バケットに移動
5) コピー先ファイルパスにファイルが生成されていれば、成功

Lambda functionのログ確認

1) Lambda
2) Lambda function名をクリック
3) Monitoring
4) 「View logs in CloudWatch」をクリック

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
19