将 PutBucketNotification 与 Amazon SDK 或 CLI 配合使用 - Amazon Simple Storage Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

PutBucketNotification 与 Amazon SDK 或 CLI 配合使用

以下代码示例演示如何使用 PutBucketNotification

CLI
Amazon CLI

将通知配置应用于名为 my-bucket 的存储桶:

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

文件 notification.json 是当前文件夹中的一个 JSON 文件,用于指定 SNS 主题和要监控的事件类型:

{ "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 事件 ObjectRemovedDelete 配置 SNS 主题配置,并为给定的 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 详细信息,请参阅《Amazon Tools for PowerShell Cmdlet 参考》中的 PutBucketNotification

有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将此服务与 Amazon SDK 结合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。