AWS lambda 在同一个 aws 账户中担任角色以访问 S3

时间:2021-01-02 10:11:54

标签: amazon-web-services amazon-s3 aws-lambda amazon-iam assume-role

我创建了一个角色来从 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 的角色名称。

是否可以在同一个帐户中担任角色?是这样,我在这里错过了什么步骤?请告诉我。

谢谢

2 个答案:

答案 0 :(得分:1)

您需要使用 trust policy

修改角色
        {
    "Version": "2012-10-17",
    "Statement": [
        {
        "Effect": "Allow",
        "Principal": {
            "Service": "lambda.amazonaws.com"
        },
        "Action": "sts:AssumeRole"
        }
    ]
    }

除此之外,请确保您的 S3 存储桶没有 bucket policy。因为基于资源的策略和基于 IAM 的策略都应该允许。

答案 1 :(得分:1)

如果两者都在同一个帐户中,则不需要在 lambda 代码中使用 STS 和 AssumeRole 来访问 S3,如果附加到 lambda 的角色具有允许在 S3 上访问的策略,它就会正常工作。

但如果你真的想这样做,你需要确保你的角色 AssumeS3RoleDemo 信任策略允许 lambda 执行角色承担它。

以下是使用两个不同帐户的一个示例的链接,但仅使用一个帐户的机制相同:
https://aws.amazon.com/premiumsupport/knowledge-center/lambda-function-assume-iam-role/#:~:text=1.,the%20role%20in%20account%20B%3A&text=Update%20your%20Lambda%20function%20code,to%20create%20a%20service%20client