Boto3 返回调用 PutObject 操作时发生错误 (AccessDenied):拒绝访问

时间:2021-05-06 10:59:23

标签: amazon-web-services amazon-s3 boto3 amazon-iam

我创建了一个用户,其策略具有对 S3 的完全访问权限: enter image description here

当我设置凭据 (~/.aws/credentials) 并尝试使用 boto3 将文件推送到我的存储桶时,它返回 An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

知道为什么会这样吗?

我什至尝试为 root 帐户生成访问密钥 ID/秘密访问密钥,但它返回相同的错误。我已经使用另一个帐户的凭据运行了我的代码,并且运行良好,因此问题出在帐户本身内。

编辑:

我使用 boto3.client('sts').get_caller_identity().get('Account') 验证了来电显示与我的帐户相同。

我没有为我的存储桶设置策略,这些是它的权限 enter image description here

这是我的课程片段

from boto3 import client
from botocore.exceptions import ClientError
from boto3.exceptions import S3UploadFailedError

class AmazonS3(object):
    s3 = client('s3')

@classmethod
def upload_image(cls, bucket_name, object_name, file_content):
    extra_args = {"ACL": "public-read",
                  "ContentType": "image/jpeg" if object_name.split('.')[-1] in ['jpg', 'jpeg'] else "image/png",
                  "ContentDisposition": "inline",
                  "ContentEncoding": "base64"}

    try:
        cls.s3.put_object(Body=file_content, Bucket=bucket_name, Key=object_name, **extra_args)
    except (ClientError, S3UploadFailedError, Exception) as e:
        raise Exception('There was an error when uploading the image')

1 个答案:

答案 0 :(得分:0)

我发现了这个问题。在我的代码中,我从这样的环境变量中获取存储桶名称 os.getenv('AWS_BUCKET_NAME', 'X')

在我的部署中,我已将 BUCKET_NAME='Y' 设置为环境变量,因此能够列出我的 S3 存储桶并在输出中获得“Y”而无法将文件上传到“X”而不是“Y”,因为在部署期间未设置 AWS_BUCKET_NAME

但错误 An error occurred (AccessDenied) when calling the PutObject operation: Access Denied 具有误导性,并说明我没有正确的权限,而不是说明存储桶可能不存在。