问题描述
{
"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 的角色名称。
是否可以在同一个帐户中担任角色?是这样,我在这里错过了什么步骤?请告诉我。
谢谢
解决方法
您需要使用 trust policy
修改角色 {
"Version": "2012-10-17","Statement": [
{
"Effect": "Allow","Principal": {
"Service": "lambda.amazonaws.com"
},"Action": "sts:AssumeRole"
}
]
}
除此之外,请确保您的 S3 存储桶没有 bucket policy。因为基于资源的策略和基于 IAM 的策略都应该允许。
,如果两者都在同一个帐户中,则不需要在 lambda 代码中使用 STS 和 AssumeRole 来访问 S3,如果附加到 lambda 的角色具有允许在 S3 上访问的策略,它就会正常工作。
但如果你真的想这样做,你需要确保你的角色 AssumeS3RoleDemo
信任策略允许 lambda 执行角色承担它。
以下是使用两个不同帐户的一个示例的链接,但仅使用一个帐户的机制相同:
https://aws.amazon.com/premiumsupport/knowledge-center/lambda-function-assume-iam-role/#:~:text=1.,to%20create%20a%20service%20client。