我创建了一个角色来从 s3 存储桶获取对象,如下所示:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "S3GetObjects",
"Effect": "Allow",
"Action": [
"s3:Get*"
],
"Resource": [
"arn:aws:s3:::cat-pics",
"arn:aws:s3:::cat-pics/"
]
}
]
}
接下来,创建一个 lambda 函数来承担此角色。为此,将以下语句添加到附加到 lambda 的基本 lambda 执行角色:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": "arn:aws:iam::same-account-id:role/AssumeS3RoleDemo"
}
]
}
但是,下面的代码
import json
import boto3
def lambda_handler(event, context):
print("this test should be printed")
# create an STS client object that represents a live connection to the
# STS service
sts_client = boto3.client('sts')
# Call the assume_role method of the STSConnection object and pass the role
# ARN and a role session name.
assumed_role_object=sts_client.assume_role(
RoleArn="arn:aws:iam::same-account-id:role/AssumeS3RoleDemo",
RoleSessionName="AssumeRoleSession"
)
# From the response that contains the assumed role, get the temporary
# credentials that can be used to make subsequent API calls
credentials=assumed_role_object['Credentials']
print("credentials are")
print(credentials)
不起作用。我不断收到以下错误:
An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:sts::same-account-id:assumed-role/lambda_basic_execution_new/AssumeRoleDemo is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::same-account-id:role/AssumeS3RoleDemo: ClientError
这里 AssumeRoleDemo 是 lambda 函数的名称,AssumeS3RoleDemo 是有权访问 S3 的角色名称。
是否可以在同一个帐户中承担角色?是的,我在这里缺少哪一步?请告诉我。
谢谢
如果您的 lambda 代码中的 STS 和 AssumeRole 位于同一帐户中,则无需使用 STS 和 AssumeRole 来访问 S3,如果附加到 lambda 的角色具有允许访问 S3 的策略,则它将正常工作。
但是如果你真的想这样做,你需要确保你的角色
AssumeS3RoleDemo
信任策略允许lambda执行角色来承担它。
下面是使用两个不同帐户的示例的链接,但仅使用一个帐户的机制是相同的:
https://aws.amazon.com/premiumsupport/knowledge-center/lambda-function-assume-iam-role/