首页 文章

boto3 s3 copyObject错误

提问于
浏览
0

我正在尝试使用lambda&boto3将文件从1个桶复制到同一个桶中的另一个前缀但是我一直收到错误:

调用CopyObject操作时发生错误(AccessDenied) .

要么

调用HeadObject操作时发生错误(403):禁止

取决于我使用的复制方法 .

lambda函数有一个分配给它的角色,我认为它赋予它所需的所有权限:

{
"Version": "2012-10-17",
"Statement": [
    {
        "Action": [
            "s3:HeadObject",
            "s3:ListObjects"
        ],
        "Resource": [
            "arn:aws:s3:::bucket-name",
            "arn:aws:s3:::bucket-name/*"
        ],
        "Effect": "Allow"
    },
    {
        "Action": [
            "s3:GetObject",
            "s3:PutObject",
            "s3:DeleteObject"
        ],
        "Resource": [
            "arn:aws:s3:::bucket-name/folderA/folderB/*",
            "arn:aws:s3:::bucket-name/folderC/folderD/*",
            "arn:aws:s3:::bucket-name/folderE/folderF/*"
        ],
        "Effect": "Allow"
    }
]
}

lambda函数是:

#connect to s3
s3 = boto3.resource('s3')

dirs = {
    "folderA/folderB": "folderC/folderD"        
}    

key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
etag = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['eTag'], encoding='utf-8')    
bucket = event['Records'][0]['s3']['bucket']['name']

filePathName = key.split("/")
sourceDir = filePathName[0] + "/" + filePathName[1]
fileName = filePathName[2]

sourceKey = sourceDir + "/" + fileName
source = {'Bucket': bucket, 'Key': sourceKey}
destination = dirs[sourceDir] + "/" + fileName

##########
# This option comes up with the An error occurred (AccessDenied) when calling the CopyObject operation. Error
###########
s3.Object(bucket, destination).copy_from(CopySource=source)

###########
## This option comes up with the An error occurred (403) when calling the HeadObject operation: Forbidden error
###########
s3.meta.client.copy(source, bucket, destination)

编辑:忘了提,如果我改变角色,它工作正常

{
"Version": "2012-10-17",
"Statement": [
    {
        "Action": [
            "s3:*"
        ],
        "Resource": [
            "arn:aws:s3:::bucket-name",
            "arn:aws:s3:::bucket-name/*"
        ],
        "Effect": "Allow"
    }

1 回答

  • 0

    我遇到了类似的问题 . 解决方案: CopySource=source 中的 source 必须是从存储桶根到实际文件的完整路径,而不是存储桶名称和密钥的字典 . 所以我认为您的代码可能必须是:

    s3.Object(bucket, destination).copy_from(CopySource=bucket + sourceDir)

相关问题