使用带有 boto3 的访问点读取和写入 from/to S3 存储桶

Read and write from/to S3 bucket using access points with boto3

我必须使用具有 boto3 的访问点访问 S3 存储桶。

我已经创建了一个允许读写的访问点(<access_point_arn> 是我的访问点 ARN):

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": ["s3:GetObject", "s3:PutObject"],
            "Resource": "<access_point_arn>/object/*"
    ]
}

在官方文档中提到了访问点,其中访问点 ARN 必须代替存储桶名称 (https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html). There are no examples on the official documentation site for developers (https://docs.aws.amazon.com/AmazonS3/latest/dev/using-access-points.html)。

所以根据信息我认为正确的使用方法是:

import boto3
s3 = boto3.resource('s3')
s3.Bucket('<access_point_arn>').download_file('hello.txt', '/tmp/hello.txt')

当我在附加了 AmazonS3FullAccess 托管策略的 Lambda 中执行此代码时,我得到一个 ClientError: An error occurred (403) when calling the HeadObject operation: Forbidden

Lambda 和 S3 访问点都连接到同一个 VPC。

替换...

"Resource": "arn:aws:s3:region_name:<12-digit account_id>:bucket_name"
s3.Bucket('bucket_name').download_file('hello.txt', '/tmp/hello.txt')

希望对您有所帮助...

我的第一个猜测是您缺少必须在 (1) 存储桶(存储桶策略)和 (2) 您在 boto3 SDK 中使用的 IAM 用户或角色上定义的权限。

(1) 从documentation可以看出

对于能够通过访问点访问对象的应用程序或用户,访问点和底层存储桶都必须允许请求

例如,您可以添加一个将访问控制委托给访问点的存储桶策略,这样您就不必指定来自访问点的每个主体。链接文档中给出了一个示例。

(2) 如您的问题所述,您已经在 LambdaExecutionRole 中使用 AmazonS3FullAccess 策略。我唯一的猜测(即发生在我身上的事情)是,例如,对您存储桶中的对象进行了 KMS 加密,并且您的角色缺少 kms 操作的权限。尝试在附加管理策略的情况下执行该功能,看看它是否有效。如果是,找出缺少哪些特定权限。

一些进一步的说明:我假设你

  • 没有限制访问点仅在特定 VPC 内可用。
  • 正在阻止 public 访问。