記事のターゲット
- S3へ置かれたファイルを使用して処理を実装したい方
- Lambda側で処理を完結させたい方
S3バケットの作成

バケット名とリージョンを指定し、その他はいったんデフォルトで作成。

Lambda関数の作成

設計図でGet S3 Objectを選択すると最初からデータ取得のコードが記述された状態で関数が作成される。

ロールは無ければ作成する。この際、S3の読み取り権限を付与する。

最後のトリガー部分では先ほど作成したバケット名を指定してEvent TypeにはPUTを指定する。S3に置かれるファイルが巨大になる想定の場合はMultipart upload completedも指定しないとLambdaが起動しないことがある。

チェックを付けているI acknowledge~の部分は、PUTトリガーされたS3にLambdaの処理でまたファイルをPUTする場合無限ループになるのわかってますか?という問いなので理解出来たらチェックを入れる。
チェックしないと関数が作成できない。

作成すると上記のように最初からある程度のコードが記述された状態になる。
19行目のgetObjectでS3からPUTされたファイルを取得している。ファイルに処理を行いたい場合はこの部分を変更する。
今回は取得したファイル内容を新たに作成したファイルに書き込んでPUTされたバケットとは別のバケットにPUTする処理を作成する。
新たにS3バケットを作成。


test-1111111111111に置かれたファイルをtest-1111111111111-afterにPUTする。

事前準備として、今のままだとLambdaからS3へのアクセス時にアクセス拒否されるのでLambda側にS3をいじる権限を付与する。
上記のように該当するLambda関数の設定→アクセス権限から実行ロールをクリックする。
ポリシーをアタッチ→AmazonS3FullAccessを選択→ポリシーをアタッチをクリックでS3への権限を与える。


コードの修正

前提として、コードを修正した際は上記のDeployボタンをクリックすると変更が反映される。
console.log('Loading function');
const aws = require('aws-sdk');
const s3 = new aws.S3({ apiVersion: '2006-03-01' });
exports.handler = async (event, context) => {
//ファイルがPUTされたバケットの情報取得
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,
};
try {
//PUTされたファイルを取得
const obj = await s3.getObject(params).promise();
const contents = obj.Body.toString();
console.log("取得したファイル内容:" + contents);
//ファイル内容に何か処理したい場合はここに処理を記述
//次にPUTするバケット名
const nextBucket = "test-1111111111111-after";
const nextKey = "after-sample.json"
const nextBody = contents;
const nextParam = {
Bucket: nextBucket,
Key: nextKey,
Body:nextBody
}
//別バケットにファイル名を変えてPUT
await s3.putObject(nextParam).promise();
} catch (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);
throw new Error(message);
}
};
上記のようにコード変更し、デプロイボタンクリック。
ここまで出来たらtest-1111111111111に以下内容のファイルをPUTする


PUTしたらtest-1111111111111-afterのバケットを見に行くと

after-sample.jsonファイルが作成されていることを確認。
ログが見たければLambdaの該当関数のページ→モニタリング→ログから確認できる。

以上S3トリガーでLambdaを動かす方法。