gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:36:44 24 4
gpt4 key购买 nike

我正在运行一个每天输出 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com