amazon-web-services - boto3.exceptions.S3UploadFailedError : An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

标签 amazon-web-services ubuntu amazon-s3 amazon-ec2 boto3

我正在运行一个每天输出 JSON 文件的 Amazon EC2 (ubuntu) 实例。我现在正在尝试将此 JSON 复制到 Amazon S3,以便最终可以将其下载到本地计算机。按照此处的说明 (reading in a file from ubuntu (AWS EC2) on local machine?),我使用 boto3 将 JSON 从 ubuntu 复制到 S3:

import boto3
print("This script uploads the SF events JSON to s3")

ACCESS_ID = 'xxxxxxxx'
ACCESS_KEY = 'xxxxxxx'
s3 = boto3.resource('s3',
         aws_access_key_id=ACCESS_ID,
         aws_secret_access_key= ACCESS_KEY)

def upload_file_to_s3(s3_path, local_path):
    bucket = s3_path.split('/')[2]
    print(bucket)
    file_path = '/'.join(s3_path.split('/')[3:])
    print(file_path)
    response = s3.Object(bucket, file_path).upload_file(local_path)
    print(response)

s3_path = "s3://mybucket/sf_events.json"
local_path = "/home/ubuntu/bandsintown/sf_events.json"
upload_file_to_s3(s3_path, local_path)

我在这里使用的凭证来自在 Amazon Identity and Access Management (IAM) 中创建新用户:附上屏幕截图。

enter image description here

但是,当我运行此脚本时,出现以下错误:
boto3.exceptions.S3UploadFailedError: Failed to upload /home/ubuntu/bandsintown/sf_events.json to mybucket/sf_events.json: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

我还尝试将 IAM 角色附加到 EC2 实例并赋予该角色完整的 s3 权限 - 但仍然没有运气(见下图)。

enter image description here

enter image description here

这似乎是一个权限问题 - 谁能告诉我如何开始解决这个问题?我需要 Amazon CLI 吗?我还在 boto3 文档中阅读,我的脚本中可能需要 aws_session_token 参数。

很简单,我迷路了。谢谢。

最佳答案

由于它是 ec2,因此您可以为实例分配 IAM 角色并为该角色分配权限。此外,您不需要在代码中硬编码凭据。

https://aws.amazon.com/premiumsupport/knowledge-center/assign-iam-role-ec2-instance/

您可以将此策略用于 S3 上传

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "statement1",
            "Effect": "Allow",
            "Action":   ["s3:PutObject","s3:PutObjectAcl"],
            "Resource": "arn:aws:s3:::examplebucket/*"
        }
    ]
}

以下是您如何将策略附加到 IAM 角色:
https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html

并将您的代码更改为:
s3 = boto3.resource('s3')

关于amazon-web-services - boto3.exceptions.S3UploadFailedError : An error occurred (AccessDenied) when calling the PutObject operation: Access Denied,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59239977/

相关文章:

python - AWS EC2 电子邮件转发 : Forward Incoming Email to an External Destination with Lambda

amazon-web-services - AWS Amplify 将 Gatsby 404 重定向到根 URL

node.js - 带有 etags 的 s3 流式传输( Node )

linux - 权限被拒绝在 ubuntu 上以 g+w 模式写入目录

ruby-on-rails - 错误 : RVM Ruby not used, 首先运行 `rvm use 1.9.1`

php - 为什么在 Ubuntu 上上传 Wordpress 插件或主题时连接会重置

visual-c++ - WinHttp 不会从 WinXP 上的 Amazon S3 下载

amazon-web-services - 自动从 DynamoDB 表和 S3 中删除数据

ubuntu - 从 Amazon S3 下载文件的速度下降到 <2 kb/s = 下载速度非常慢(在上传文件的机器上)

javascript - 无法成功上传图片到s3然后查看