Amazon S3 イベント通知の s3:TestEvent を処理する

Amazon S3 イベント通知の s3:TestEvent を処理する

Amazon S3 はイベント通知の設定時に s3:TestEvent メッセージを送信します。通常のイベント通知とは構造が異なるため、コンシューマー側で個別に処理する必要があります。

Takahiro Iwasa
3 min read

S3 バケットにイベント通知を設定すると、Amazon S3 から s3:TestEvent メッセージが自動的に送信されます。通常の S3 イベント通知とは構造が異なるため、コンシューマー側で個別に処理する必要があります。

https://docs.aws.amazon.com/AmazonS3/latest/userguide/notification-content-structure.html

When you configure an event notification on a bucket, Amazon S3 sends a test message with the s3:TestEvent.

構築

CloudFormation スタックのテンプレートを作成します。

template.yaml
AWSTemplateFormatVersion: "2010-09-09"
Description: Example of CloudWatch events not queueing to SSE SQS
Resources:
Bucket:
Type: AWS::S3::Bucket
Properties:
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
NotificationConfiguration:
QueueConfigurations:
- Event: 's3:ObjectCreated:Put'
Queue: !GetAtt Queue.Arn
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
Queue:
Type: AWS::SQS::Queue
Properties:
QueueName: s3-event-notification-test-queue
ReceiveMessageWaitTimeSeconds: 20
QueuePolicy:
Type: AWS::SQS::QueuePolicy
Properties:
PolicyDocument:
Version: '2008-10-17'
Statement:
- Effect: Allow
Principal:
Service: s3.amazonaws.com
Action:
- SQS:SendMessage
- SQS:ReceiveMessage
Resource: !GetAtt Queue.Arn
Condition:
StringEquals:
aws:SourceAccount: !Ref AWS::AccountId
Queues:
- !Ref Queue

スタックをデプロイします。

Terminal window
aws cloudformation deploy \
--template-file template.yaml \
--stack-name s3-event-notification-test

テスト

SQS キューをポーリングし、通知設定が機能していることを確認します。

Terminal window
aws sqs receive-message \
--queue-url https://sqs.ap-northeast-1.amazonaws.com/{AccountId}/s3-event-notification-test-queue

バケットにオブジェクトを一つも追加していなくても、出力の中に s3:TestEvent メッセージが確認できるはずです。

{
"Messages": [
{
"MessageId": "...",
"ReceiptHandle": "...",
"MD5OfBody": "...",
"Body": "{\"Service\":\"Amazon S3\",\"Event\":\"s3:TestEvent\",\"Time\":\"2020-12-29T18:53:47.874Z\",\"Bucket\":\"s3-event-notification-test-bucket-xxxxxxxx\",\"RequestId\":\"...\",\"HostId\":\"...\"}"
}
]
}

後片付け

作業後はスタックを削除します。

Terminal window
aws cloudformation delete-stack --stack-name s3-event-notification-test

まとめ

SQS イベント通知を設定した S3 バケットをデプロイすると、オブジェクトをアップロードする前に s3:TestEvent メッセージが届きます。このテンプレートでは s3:ObjectCreated:Put だけを設定していますが、テストメッセージは通知設定の作成時に自動送信されます。通常の S3 イベント通知とは異なり、最上位に ServiceEvent フィールドがあり、Records 配列はありません。

このキューを消費する Lambda 関数やアプリケーションでは、s3:TestEvent を検出してスキップするか、明示的に処理してください。すべてのメッセージに Records が含まれると仮定すると、通知設定の作成直後に処理が失敗する可能性があります。

About the author

Takahiro Iwasa

Takahiro Iwasa

Software Developer

This blog shares technical notes from hands-on projects—architecture, implementation, and AWS service integrations.