使用 Boto3 访问另一个账户中的 S3 存储桶时,Lambda 超时
我正在尝试使用 boto3 从我的 AWS Lambda 访问另一个账户中的 S3 存储桶.以下是我配置的步骤.:
1. 在我的 Lambda 所在的账户 A 中,我创建了执行角色 (Lambda-S3-SNS-VPC-Role) 并将一个 AmazonS3FullAccess 托管策略和一个内联策略附加到它:
I am trying to access S3 bucket in another account from my AWS Lambda using boto3. Below are the steps I configured.:
1. In Account A where my Lambda is I create Execution role (Lambda-S3-SNS-VPC-Role) and attach to it one AmazonS3FullAccess Managed Policy and one Inline policy as:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1489133353000",
"Effect": "Allow",
"Action": [
"sts:AssumeRole"
],
"Resource": [
"arn:aws:iam::<Account-B-ID>:role/access-s3-bucket-from-lambda-in-another-acc-role"
]
}
]
}
在我的 S3 存储桶所在的账户-B 中,我创建了一个 IAM 角色(access-s3-bucket-from-lambda-in-another-acc-role),如下所示:- 附加 AmazonS3FullAccess 托管策略和信任关系:
In Account-B, where my S3 bucket is present, I created one IAM Role (access-s3-bucket-from-lambda-in-another-acc-role) as below: - Attached AmazonS3FullAccess managed policy and in Trust Relationship :
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::<Account-A-ID>:role/Lambda-S3-SNS-VPC-Role",
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
此外,在账户 B 的 S3 存储桶中,给出了以下存储桶策略
Also, in S3 Bucket in account B, gave below bucket policy
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::<Account-A-ID>:role/Lambda-S3-SNS-VPC-Role"
},
"Action": "s3:*",
"Resource": [
"arn:aws:s3:::my-bucket-in-acc-B",
"arn:aws:s3:::my-bucket-in-acc-B/*"
]
}
]
}
以下是我的 Lambda 函数代码:
Below is my Lambda Function code:
def lambda_handler(event, context):
sts_connection = boto3.client('sts')
acct_b = sts_connection.assume_role(
RoleArn="arn:aws:iam::<Account-B-ID>:role/access-s3-bucket-from-lambda-in-another-acc-role",
RoleSessionName="cross_acct_lambda"
)
print('acct_b: ',acct_b)
但是在测试时,什么也没有发生,函数超时了.请指导.
But while testing, nothing is happening and the Function gets timed out. Please guide.
我不确定您的函数为什么会超时,但我想推荐一种不同的方法:
I'm not sure why your function is timing-out, but I'd like to recommend a different approach:
-
Account-A
中使用 IAM 角色运行的 Lambda 函数Lambda-S3-SNS-VPC-Role
-
Bucket-B
在Account-B
中,具有允许从Lambda-S3-SNS-VPC-Role
访问的 Bucket 策略(此和你上面显示的完全一样)
- Lambda function in
Account-A
that runs with IAM RoleLambda-S3-SNS-VPC-Role
-
Bucket-B
inAccount-B
with a Bucket policy that permits access fromLambda-S3-SNS-VPC-Role
(this is exactly as you have shown above)
这就是你所需要的!
无需承担来自 Account-B
的 IAM 角色,因为 Bucket-B
上的存储桶策略允许从Lambda 函数使用的 IAM 角色.
There is no need to assume an IAM Role from Account-B
because the Bucket Policy on Bucket-B
is permitting the access from the IAM Role used by the Lambda function.