ablog

不器用で落着きのない技術者のメモ

S3 イベント通知はオブジェクト作成完了後に通知されることを確認する

S3イベント通知を使うと、S3バケットにファイルが作成されたり削除されたのをトリガーにイベントドリブンで、Lambda関数をキックしたり、SNSやSQSにメッセージを送ったりすることができるが、作成や削除が開始したタイミングではなく完了したタイミングでイベント通知が行われることを確認した。S3は結果整合性のため、完了していてもアクセス時にファイルが見つからないことは起こり得る。

事前準備

export LANG=C
export TZ=UTC
export AWS_DEFAULT_REGION=ap-northeast-1
SNSトピックを作成する
  • 既存のSNSトピック名を確認する
aws sns list-topics
  • SNSトピックを作成する
aws sns create-topic --name s3-event-test
  • トピックを subscribe する(指定したメールアドレスに通知する)
aws sns subscribe --topic-arn arn:aws:sns:ap-northeast-1:*********:s3-event-test \
	--protocol email \
	--notification-endpoint ******@gmail.com
  • 指定したメールアドレスに確認メールが届くので本文のリンクをクリックする。
Subject: AWS Notification - Subscription Confirmation
Body:
You have chosen to subscribe to the topic: 
arn:aws:sns:ap-northeast-1:*********:s3-event-test

To confirm this subscription, click or visit the link below (If this was in error no action is necessary): 
Confirm subscription
S3バケットを作成する
aws s3 mb s3://az-test-2018
  • S3 にファイルが copy されたら SNS トピックに通知されるよう設定する。
    • 以下の内容でファイルを作成する。
{
    "TopicConfigurations": [
        {
            "TopicArn": "arn:aws:sns:ap-northeast-1:********:s3-event-test",
            "Events": [
                "s3:ObjectCreated:*"
            ]
        }
    ]
}
aws s3api put-bucket-notification-configuration --bucket "az-test-2018" --notification-configuration file://topic_config.json

試してみる

  • ファイルを作成する
$ perl -le 'print for 1..100000000' > test.txt
$ ls -lh test.txt
-rw-r--r--  1 yohei-a  1896053708   848M Feb 11 10:22 test.txt

S3に copy 時に通知される時刻を確認する

  • S3にファイルをアップロードする
date; aws s3 cp test.txt s3://az-test-2018/; date