S3バケットにイベント通知を設定する – AWS SDK for JavaScript v3
既存S3バケットにイベント通知を設定します。
プロジェクト作成
npmプロジェクト作成します。npm init -y@aws-sdk/client-s3をインストールします。
npm i @aws-sdk/client-s3ESMにするためにpackage.jsonに
"type": "module"
を1行追加します。 { "name": "lambda-s3-notification", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "type": "module", "keywords": [], "author": "", "license": "ISC", "dependencies": { "@aws-sdk/client-s3": "^3.129.0" } }
Lambda(node.js v16)
バケット名、LambdaのARNは設定が必要です。import { PutBucketNotificationConfigurationCommand , S3Client } from '@aws-sdk/client-s3' const bucketname = 'バケット名' export async function handler(event, context) { const client = new S3Client({ region: 'ap-northeast-1' }) const input = { Bucket: bucketname, NotificationConfiguration: { LambdaFunctionConfigurations: [{ LambdaFunctionArn: 'LambdaのARN', Events: ['s3:ObjectCreated:Put'] // ここではPut }] } } const command = new PutBucketNotificationConfigurationCommand(input) const response = await client.send(command) return { statusCode: 200, body: `Hello` } }
レスポンス
こんな感じです。httpStatuscodeが200ならうまくいっているはずです。{ '$metadata': { httpStatusCode: 200, requestId: undefined, extendedRequestId: 'vUnKAdb+fmmacGYe4ebD/8thtUNFWnttlPBcda5zIWTSE5tuUUvLlqGFDatcZQd/WvKKxmDrcK4=', cfId: undefined, attempts: 1, totalRetryDelay: 0 } }
注意
既に設定されているトリガーの設定は上書きされてしまい、削除されてしまいます。 上書きされない様、追加されるLambdaにします。↓既存のトリガー設定を保持しつつ、新規トリガーを追加するLambda(node.js v16)
この続きを読むには
コメント