Ala*_*ACK 2 python amazon-s3 amazon-web-services boto3 aws-lambda
目前,我正在尝试动态创建event
on a来调用 lambda 函数,每当类似或 之类bucket
的触发器发生时。s3:ObjectCreated:*
s3:ObjectRemoved:*
我有以下代码
import boto3
client = boto3.client('s3',
aws_access_key_id="...",
aws_secret_access_key="...",
region_name="us-east-1")
response = client.put_bucket_notification(
Bucket='my_test_bucket',
NotificationConfiguration={
'CloudFunctionConfiguration': {
'Id': event_name,
'Events': [
's3:ObjectCreated:*',
's3:ObjectRemoved:*',
],
'CloudFunction': 'arn:aws:lambda:...',
}
}
)
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试运行代码时,出现以下错误
An error occurred (InvalidArgument) when calling the PutBucketNotification
operation: Unable to validate the following destination configurations
Not authorized to invoke function [arn:aws:lambda:...]
Run Code Online (Sandbox Code Playgroud)
如何以编程方式授予my_test_bucket
运行权限arn:aws:lambda:...
?
请参阅官方文档,您使用的方法已被弃用,虽然为了向后兼容性而维护它,但它可能无法按预期运行。浏览此处获取更多信息; 您应该使用PutBucketNotificationConfiguration
bucket_notification.put ()。
尽管如此,您看到的错误是:
Not authorized to invoke function [arn:aws:lambda:...]
这是因为当您的 Lambda 执行时,调用它的服务需要调用它的权限;您只需授予 S3 调用 Lambda 的权限。您可以通过为 Lambda 创建资源策略来实现此目的。
在 Python 中,你将这样做:
client = boto3.client('lambda')
response = client.add_permission(
FunctionName='arn:aws:lambda:...',
StatementId='LambdaInvoke',
Action='lambda:InvokeFunction',
Principal='s3.amazonaws.com',
SourceArn='arn:aws:s3:::my_test_bucket',
SourceAccount='123456789012'
)
Run Code Online (Sandbox Code Playgroud)
不要忘记将 替换function-name
为您的函数 ARN,并将 替换source-arn
为您的 S3 存储桶 ARN,并将source-account
替换为源帐号。
另一种方法是,如果您想从 CLI 执行此操作,可以这样做:
aws lambda add-permission --function-name arn:aws:lambda:... --principal s3.amazonaws.com --statement-id S3EventTrigger --action "lambda:InvokeFunction" --source-arn arn:aws:s3:::my_test_bucket --source-account 123456789012
Run Code Online (Sandbox Code Playgroud)
这两种方法都会将资源策略(如下所示的策略)附加到您的 Lambda,允许您的 S3 存储桶调用它。
{"Policy" : "{"Version":"2012-10-17","Id":"default","Statement":[{"Sid":"S3EventTrigger","Effect":"Allow","Principal":{"Service":"s3.amazonaws.com"},"Action":"lambda:InvokeFunction","Resource":"arn:aws:lambda:...","Condition":{"StringEquals":{"AWS:SourceAccount":"123456789012"},"ArnLike":{"AWS:SourceArn":"arn:aws:s3:::my_test_bucket"}}}]}" ,
"RevisionId" : "999a9999-99ab-9999-a9a9-9999999a999a"}
Run Code Online (Sandbox Code Playgroud)