I am trying to upload file to s3 in python. So far now my code is like this
import boto3
from botocore.exceptions import NoCredentialsError
ACCESS_KEY = 'XXXXXXXXXXXX'
SECRET_KEY = 'XXXXXXXXXXXX'
def upload_to_aws(local_file, bucket, s3_file):
s3 = boto3.client('s3', aws_access_key_id=ACCESS_KEY,
aws_secret_access_key=SECRET_KEY)
try:
s3.upload_file(local_file, bucket, s3_file)
print("Upload Successful")
return True
except FileNotFoundError:
print("The file was not found")
return False
except NoCredentialsError:
print("Credentials not available")
return False
uploaded = upload_to_aws('image-1.png', 'bucketname', 'image-1.png')
But when I am trying to run the code its showing error like
boto3.exceptions.S3UploadFailedError: Failed to upload image-1.png to bucketname/image-1.png: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied
I have checked the bucket permission and its fine. The permission is like this:
Block all public access
Off
Block public access to buckets and objects granted through new access control lists (ACLs)
Off
Block public access to buckets and objects granted through any access control lists (ACLs)
Off
Block public access to buckets and objects granted through new public bucket policies
On
Block public and cross-account access to buckets and objects through any public bucket policies
On
couple things:
- make sure that you actually created the security credential successfully via the dashboard
- did you create the bucket? if the bucket was not created and the user group your security credential corresponds to doesn’t have permission to upload to that bucket, then you wouldn’t be able to put objects into that bucket, right?
- minor detail: please use environment variables instead of copy-paste your credentials to the script
import os
ACCESS_KEY = os.environ['access_key_id']
SECRET_KEY = os.environ['secret_access_key']