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

Question:

I’m running an Amazon EC2 (ubuntu) instance which outputs a JSON file daily. I am now trying to copy this JSON to Amazon S3 so that I can eventually download it to my local machine. Following the instructions here (reading in a file from ubuntu (AWS EC2) on local machine?), I’m using boto3 to copy the JSON from ubuntu to S3:

The credentials I’m using here are from creating a new user in Amazon Identity and Access Management (IAM): screenshot attached.

enter image description here

However, when I run this script, I get the following error:

I’ve also tried attaching an IAM role to the EC2 instance and given that role full s3 permissions – but still no luck (see image below).

enter image description here

enter image description here

It appears to be a permissions issues – can anyone tell me how I might begin to solve this? Do I need Amazon CLI? I’m also reading in boto3 documentation that I may need an aws_session_token parameter in my script.

Quite simply, I’m lost. Thanks.

Answer:

Since it’s an ec2, you can assign an IAM role to the instance and assign permissions to the role. Also you don’t need to hardcode the credentials in your code.

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

You can use this policy for S3 upload

here is how you attach policies to IAM role:
https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html

and change your code to:

Leave a Reply