搭PutBucketNotification配 AWS SDK 或命令列工具使用 - Amazon Simple Storage Service

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

PutBucketNotification配 AWS SDK 或命令列工具使用

下列程式碼範例會示範如何使用PutBucketNotification

CLI
AWS CLI

會將通知組態套用至名為my-bucket

aws s3api put-bucket-notification --bucket my-bucket --notification-configuration file://notification.json

該檔案notification.json是指定要監視的 SNS 主題和事件類型的目前資料夾中的 JSON 文件:

{ "TopicConfiguration": { "Event": "s3:ObjectCreated:*", "Topic": "arn:aws:sns:us-west-2:123456789012:s3-notification-topic" } }

SNS 主題必須附加 IAM 政策,以便讓 Amazon S3 發佈到該主題:

{ "Version": "2008-10-17", "Id": "example-ID", "Statement": [ { "Sid": "example-statement-ID", "Effect": "Allow", "Principal": { "Service": "s3.amazonaws.com" }, "Action": [ "SNS:Publish" ], "Resource": "arn:aws:sns:us-west-2:123456789012:my-bucket", "Condition": { "ArnLike": { "aws:SourceArn": "arn:aws:s3:*:*:my-bucket" } } } ] }
PowerShell
適用的工具 PowerShell

範例 1:此範例設定 S3 事件的 SNS 主題組態, ObjectRemovedDelete 並啟用指定 s3 儲存貯體的通知

$topic = [Amazon.S3.Model.TopicConfiguration] @{ Id = "delete-event" Topic = "arn:aws:sns:eu-west-1:123456789012:topic-1" Event = [Amazon.S3.EventType]::ObjectRemovedDelete } Write-S3BucketNotification -BucketName kt-tools -TopicConfiguration $topic

範例 2:此範例會啟 ObjectCreatedAll 用將其傳送至 Lambda 函數的指定儲存貯體的通知。

$lambdaConfig = [Amazon.S3.Model.LambdaFunctionConfiguration] @{ Events = "s3:ObjectCreated:*" FunctionArn = "arn:aws:lambda:eu-west-1:123456789012:function:rdplock" Id = "ObjectCreated-Lambda" Filter = @{ S3KeyFilter = @{ FilterRules = @( @{Name="Prefix";Value="dada"} @{Name="Suffix";Value=".pem"} ) } } } Write-S3BucketNotification -BucketName ssm-editor -LambdaFunctionConfiguration $lambdaConfig

範例 3:此範例會根據不同的索引鍵尾碼建立 2 個不同的 Lambda 組態,並在單一命令中進行設定。

#Lambda Config 1 $firstLambdaConfig = [Amazon.S3.Model.LambdaFunctionConfiguration] @{ Events = "s3:ObjectCreated:*" FunctionArn = "arn:aws:lambda:eu-west-1:123456789012:function:verifynet" Id = "ObjectCreated-dada-ps1" Filter = @{ S3KeyFilter = @{ FilterRules = @( @{Name="Prefix";Value="dada"} @{Name="Suffix";Value=".ps1"} ) } } } #Lambda Config 2 $secondlambdaConfig = [Amazon.S3.Model.LambdaFunctionConfiguration] @{ Events = [Amazon.S3.EventType]::ObjectCreatedAll FunctionArn = "arn:aws:lambda:eu-west-1:123456789012:function:verifyssm" Id = "ObjectCreated-dada-json" Filter = @{ S3KeyFilter = @{ FilterRules = @( @{Name="Prefix";Value="dada"} @{Name="Suffix";Value=".json"} ) } } } Write-S3BucketNotification -BucketName ssm-editor -LambdaFunctionConfiguration $firstLambdaConfig,$secondlambdaConfig
  • 如需 API 詳細資訊,請參閱AWS Tools for PowerShell 指令程PutBucketNotification式參考中的。

如需 AWS SDK 開發人員指南和程式碼範例的完整清單,請參閱透過 AWS SDK 使用此服務。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。