
Managing EC2 Access to S3 with IAM Role-based Permissions (No Hardcoded Credentials)
A hands-on guide to accessing S3 from EC2 using IAM roles instead of access keys — temporary credentials, least-privilege policies.
If you've ever put an access key and secret key inside
~/.aws/credentials on an EC2 instance just to let it talk to S3, you're not alone — it's the path of least resistance, and it's also one of the most common AWS security mistakes.In this post, I'll walk through the right way to do it: using an IAM role so the instance gets temporary, auto-rotating credentials with zero secrets stored on disk. By the end, an EC2 instance will be able to upload, list, and download objects from a private S3 bucket without a single key ever touching it.
What you'll need: an AWS account, basic familiarity with the EC2 and IAM consoles, and an SSH client.
Project Architecture

Why Not Just Use Access Keys?
The "quick" way to let an EC2 instance talk to S3 is to generate an IAM user's access key/secret key and drop them into
~/.aws/credentials on the instance. It works, but it's a bad habit for a few reasons:- Long-lived credentials sitting on disk — anyone who compromises the instance (or finds the keys in an AMI snapshot, a backup, or a leaked
.bash_history) gets standing access to your AWS account.
- No automatic rotation — you have to manually rotate and redistribute keys, and in practice this rarely happens, so the same key can live for years.
- Hard to scope tightly per-instance — the same key often gets reused across multiple servers, so a single leak has a wide blast radius.
- Easy to accidentally commit — hardcoded keys have a way of ending up in git history, Docker images, or CI logs.
IAM roles solve all of this using temporary, auto-rotating credentials delivered to the instance via the EC2 Instance Metadata Service (IMDS). The AWS CLI and SDKs check IMDS automatically, so nothing needs to be hardcoded — that's why the first upload attempt below fails with
Unable to locate credentials , and why it starts working the moment a role is attached, with zero config changes on the instance itself.
Step 1: Create a Private S3 Bucket
Create a new S3 bucket with default settings, and make sure Block all public access stays checked. This bucket will hold the test file we upload later.
Step 2: Launch an EC2 Instance
Launch an EC2 instance with a public IP, your key pair, and a security group that allows inbound SSH (port 22).
Step 3: SSH In and Prepare the Instance
ssh -i /path/to/your-key-pair.pem <username>@ec2-public-ip
Install the AWS CLI on the instance:
sudo apt install awscli -y# or, on Amazon Linux / RHEL-based systems:sudo dnf install awscli -y
Create a test file to upload to the private S3 bucket:
echo "welcome to private s3 bucket" > test.txt
Now try uploading it — this should fail:
root@ip-172-31-22-21:~# aws s3 cp test.txt s3://my-s3-janakupload failed: ./test.txt to s3://my-s3-janak/test.txt Unable to locate credentialsroot@ip-172-31-22-21:~#
This error is expected — and it's the whole point of the demo. The instance has no credentials configured anywhere (no
aws configure , no environment variables, no access keys), which proves that whatever access it gets later is coming purely from the IAM role, not from something typed in manually.
Step 4: Create an IAM Policy

- In the IAM console, click Policies in the left sidebar
- Click Create policy
- Select the JSON tab
- Clear the existing content and paste the following (replace
my-s3-janakwith your bucket name):
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:ListBucket" ], "Resource": "arn:aws:s3:::my-s3-janak" }, { "Effect": "Allow", "Action": [ "s3:GetObject", "s3:PutObject" ], "Resource": "arn:aws:s3:::my-s3-janak/*" } ]}
- Click Next, give it a policy name (e.g.
my-s3-janak), then click Create policy
Why two statements?
s3:ListBucket is a bucket-level action, so its Resource points to the bucket ARN itself ( arn:aws:s3:::my-s3-janak ). s3:GetObject and s3:PutObject are object-level actions, so they need the /* suffix to apply to objects inside the bucket. Mixing these up — say, granting GetObject on the bare bucket ARN without /* — is one of the most common IAM policy mistakes, and AWS won't warn you about it. It just silently returns Access Denied at runtime.This policy also follows the principle of least privilege: it grants access to exactly one bucket, and only the three actions actually needed (list, read, write) — not blanket
s3:* access.
Step 5: Create an IAM Role

- In IAM, click Roles → Create role
- Trusted entity type:
AWS service→ Use case:EC2→ click Next
- Attach permissions: search for and select the
my-s3-janakpolicy → click Next
- Name and review:
- Role name:
my-s3-janak
- Description:
IAM role for EC2 to access S3
- Click Create role
An IAM role is different from an IAM user — a role isn't tied to a specific person; it's an identity that something (in this case, the EC2 service) can assume temporarily. When you pick "AWS service → EC2" as the trusted entity, AWS attaches a trust policy behind the scenes that allows
ec2.amazonaws.com to assume this role. That trust relationship is what lets EC2 automatically request and refresh temporary credentials on the role's behalf via IMDS — no manual credential handling required.
Step 6: Attach the Role to the EC2 Instance

- Go to EC2 Dashboard → Instances
- Select your instance
- Actions → Security → Modify IAM role
- IAM role: select
my-s3-janak
- Click Update IAM role
Behind the scenes, attaching the role creates an instance profile — a lightweight container that associates the IAM role with the EC2 instance. This is why the console sometimes shows an instance profile with the same name as the role; it's created and linked automatically, so you rarely need to think about it separately.
No reboot is needed. The instance immediately starts receiving temporary security credentials (access key, secret key, and session token) via IMDS, which AWS rotates automatically roughly every few hours — which is exactly why the CLI just works on the very next command, with zero configuration changes.
Step 7: Upload txt file from EC2 instance to S3 private bucket.
# Upload to S3aws s3 cp test.txt s3://my-s3-janak/# upload: ./test.txt to s3://my-s3-janak/test.txt
# List bucket contentsaws s3 ls s3://my-s3-janak/# 2026-08-12 15:30:00 5 test.txt
# Download the fileaws s3 cp s3://my-s3-janak/test.txt downloaded.txt# download: s3://my-s3-janak/test.txt to ./downloaded.txt

The exact same
aws s3 cp command that failed earlier with Unable to locate credentials now works — without installing new packages, without running aws configure , and without a single key ever touching the instance's disk. The AWS CLI transparently discovered the role's temporary credentials through IMDS and used them for the request.
Key Takeaways
- No hardcoded credentials — the instance never stores an access key or secret key anywhere.
- Temporary, auto-rotated credentials — reduces the blast radius if the instance is ever compromised.
- Least-privilege IAM policy — the role can only touch this one bucket, and only list/get/put — nothing else.
- This pattern scales — the same approach (IAM role → instance profile → least-privilege policy) is exactly how Lambda functions, ECS tasks, and other AWS compute services are meant to access resources like S3, DynamoDB, or Secrets Manager — instead of embedding credentials in code or environment variables.
If you're setting up anything on AWS that needs to talk to another AWS service, reach for an IAM role first. Access keys should be the exception, not the default.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article