且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Amazon S3在另一个帐户中触发另一个Lambda函数

更新时间:2023-11-27 22:39:16

@John的解决方案有效,但是我想在他的答案中添加一些步骤.

@John's Solution works but there are certain steps I would like to add to his answer.

  • S3 存储桶和 Lambda 必须位于同一区域.例如,两者都应在us-east-1区域中创建.不同地区会引发如下错误:
  • The S3 bucket and the Lambda need to be in the same region. For example, both should be created in us-east-1 region. Different regions would throw an error as below:

通知目的地服务区域对于存储桶位置约束无效

The notification destination service region is not valid for the bucket location constraint

下面是我创建触发器的步骤:

Below is the Steps I followed to create the trigger:

Account-A.S3-bucket -> Account-B.Lambda-function

  1. 从终端上,切换到Lambda所在的Account-B的AWS配置文件
  2. 运行以下命令,为您的情况更改参数:

  1. From Terminal, switch to Account-B's AWS profile where the Lambda would reside
  2. Run the below command, change the parameters for your case:

aws lambda add-permission \ --region {Account-B.Lambda region Eg. us-east-1} \ --function-name {Account-B.Lambda name} \ --statement-id 1 \ --principal s3.amazonaws.com \ --action lambda:InvokeFunction \ --source-arn arn:aws:s3:::{Account-A.S3 name} \ --source-account {Account-A.account-id} \ --profile {Account-B.profile-name}

aws lambda add-permission \ --region {Account-B.Lambda region Eg. us-east-1} \ --function-name {Account-B.Lambda name} \ --statement-id 1 \ --principal s3.amazonaws.com \ --action lambda:InvokeFunction \ --source-arn arn:aws:s3:::{Account-A.S3 name} \ --source-account {Account-A.account-id} \ --profile {Account-B.profile-name}

在这种情况下,您可能会得到statement-id存在错误,增加statement-id并再次运行命令.

You might get statement-id exists error, increment statement-id and re-run command again in this case.

  1. 转到Account-A S3 存储桶,然后在事件
  2. 下的属性标签下>
  3. 选择添加通知
  4. 添加以下字段:

  1. Go to Account-A's S3 bucket and under Properties's tab > under Events
  2. Select Add Notification
  3. Add the following fields:

Name: ObjectCreation Events: ObjectCreate (All) Send to: Lambda function Lambda: Add Lambda function ARN Lambda function ARN: your-lambda-arn

Name: ObjectCreation Events: ObjectCreate (All) Send to: Lambda function Lambda: Add Lambda function ARN Lambda function ARN: your-lambda-arn

注意:Lambda函数可能仍然显示错误,但是在S3存储桶中添加的新对象会触发lambda,并且print(event)日志会出现在Cloudwatch日志中.

Note: The Lambda function might still show an error but new objects added in the S3 bucket trigger the lambda and print(event) logs appear in Cloudwatch logs.