AWS Fundamentals Series

🔐 The Top 1% Hands-On for Never Giving EC2 an Access Key: Escaping Hardcoded Credentials With an IAM Role

Introduction

This article is part of the Top 1% Series Complete Article Guide, the 3rd article in the AWS Fundamentals Series.

Prerequisites

Why Hardcoding an Access Key Is a Problem in the First Place

Say an application running on EC2 needs to read a file from an S3 bucket. The easiest approach is to create an IAM user, issue its access key and secret key, and write them directly into the application’s config file or code. But this approach has a serious problem. If that EC2 instance is ever compromised in any way, an attacker can simply steal this static access key as-is. This access key has no expiration — unless an administrator deliberately rotates (updates or revokes) it, it stays valid indefinitely, even after being stolen. On top of that, copying the same credentials around to multiple servers makes it a headache to track which server is even using which credential.

The Big Picture

This hands-on consists of five steps.

graph LR
    Step0["Step0<br/>Set up a test<br/>S3 bucket"]
    Step1["Step1<br/>Create a least-privilege<br/>IAM role"]
    Step2["Step2<br/>Attach the role to<br/>the EC2 instance"]
    Step3["Step3<br/>Access S3 with<br/>no credentials configured"]
    Step4["Step4<br/>Confirm access outside<br/>the role's scope fails"]
    Step0 --> Step1 --> Step2 --> Step3 --> Step4

Hands-On Steps

Step 0: Set up a test S3 bucket

Create a test S3 bucket for this hands-on to target, and upload some arbitrary file into it (run this from the environment in Understanding EC2 Key Pairs and Reserved Subnet IPs, or from your own machine).

aws s3 mb s3://my-allowed-bucket-<a unique string, like your own name>
echo "test file" > test.txt
aws s3 cp test.txt s3://my-allowed-bucket-<a unique string, like your own name>/

A bucket name must be unique across all of AWS, so replace <a unique string, like your own name> with something that won’t collide with anyone else’s. From here on, this bucket is referred to as my-allowed-bucket.

Step 1: Create a least-privilege IAM role

Create an IAM policy and role that only permits read-only access to one specific S3 bucket.

aws iam create-role --role-name EC2-S3-ReadOnly-Role --assume-role-policy-document '{
  "Version": "2012-10-17",
  "Statement": [{"Effect": "Allow", "Principal": {"Service": "ec2.amazonaws.com"}, "Action": "sts:AssumeRole"}]
}'

This AssumeRolePolicyDocument (the trust policy) specifies that “only the EC2 service is permitted to assume this role.” Separately from this, attach a permissions policy that actually grants read access to S3, scoped to exactly one specific bucket.

Step 2: Attach the role to the EC2 instance

Attach the role you created to your target EC2 instance. Replace i-xxxxxxxx with the actual instance ID of the instance you launched in the previous hands-on. You can find the instance ID on the EC2 console’s instance list screen, or with this command.

aws ec2 describe-instances --query "Reservations[].Instances[].{ID:InstanceId,Name:Tags[?Key=='Name']|[0].Value}" --output table
aws ec2 associate-iam-instance-profile --instance-id i-xxxxxxxx --iam-instance-profile Name=EC2-S3-ReadOnly-Role

This can be done against a running instance, with no restart required.

Step 3: Access S3 with no credentials configured

SSH into that EC2 instance, and without ever running aws configure, run the following.

aws s3 ls s3://my-allowed-bucket/

Confirm this command succeeds, even though you never configured an access key or secret key at all. The AWS CLI automatically queries the instance metadata service and retrieves temporary credentials for the role attached to that instance, on its own.

Step 4: Confirm access outside the role’s scope fails

Now try accessing a different S3 bucket, one the role’s policy doesn’t permit.

aws s3 ls s3://some-other-bucket/

Confirm you get an Access Denied error. This shows that the permission granted to the role is exactly as scoped as intended — to one specific bucket only.

What a Pro Sees Here (Top 1% Understanding)

An IAM role’s credentials are temporary, issued by STS

The credentials an instance with an IAM role attached actually uses aren’t a static access key at all. A mechanism called STS (Security Token Service) automatically issues temporary, time-limited credentials. These temporary credentials automatically refresh every few hours by default. In other words, even if these temporary credentials were ever leaked, they’d simply expire and become invalid on their own. Compared to a static access key that requires a human to deliberately rotate it, this property — automatically becoming invalid even if left alone — is exactly why an IAM role is considered fundamentally safer.

The instance metadata service, and why IMDSv2 became mandatory

Behind the scenes of the AWS CLI automatically retrieving credentials in Step 3 is a mechanism called the instance metadata service, which the EC2 instance itself queries at the special address 169.254.169.254. This mechanism has an older version (IMDSv1) and a newer one (IMDSv2). IMDSv1 lets credentials be retrieved with nothing more than a simple HTTP GET request, which means that if the application itself has a vulnerability called SSRF (Server-Side Request Forgery), an external attacker can use that application as a stepping stone to indirectly steal the instance’s credentials — this has actually been exploited in the real world. IMDSv2 prevents this class of attack by requiring an additional step: fetching a token first. Always enable the setting that requires IMDSv2 on any newly launched instance.

Common Misconceptions and Pitfalls

Troubleshooting Perspective

  1. You attached the role, but still get Access Denied: Check both the trust policy (who can assume this role) and the permissions policy (what this role can actually do). Even if the former allows the EC2 service, it fails if the latter doesn’t grant access to the target bucket.
  2. The aws s3 ls command itself errors with credentials not found: Check whether the role is actually correctly attached to the instance, with aws ec2 describe-iam-instance-profile-associations.
  3. Queries to the instance metadata service time out: If IMDSv2 is set to required, an older version of the AWS CLI or SDK may fail to correctly fetch the token. Update it.

Summary

Takeaways to Apply Today

  1. When launching a new EC2 instance, first consider whether an IAM role can achieve what you need, and avoid hardcoding an access key.
  2. Always enable the setting requiring IMDSv2 on new instances.

References

Comments

Feel free to leave thoughts, questions, or corrections below (sign in with a GitHub account to comment or react).