Ravindra BagaleCourses & study guides

Guides

How to Attach an IAM Role to an EC2 Instance (No Access Keys)

To attach an IAM role to an EC2 instance, create a role in IAM with trusted entity AWS service → EC2 and only the permissions the instance needs, then in the EC2 console select the instance → Actions → Security → Modify IAM role → choose the role → Update IAM role. The AWS CLI and SDKs on the instance then get temporary credentials automatically, with no access keys stored on the server. Check it with aws sts get-caller-identity.

Friends, running aws configure on EC2 and typing in your own access key is the biggest mistake students make. If the server is compromised, the attacker gets your whole account. The fix: an IAM role. Example: your web server puts its backup into an S3 bucket every night – without using a single key. Let's create the role and attach it.

Quick answer

Console: IAM → Roles → Create role → AWS service → EC2 → attach a policy (e.g. read access to one S3 bucket) → name web-s3-role → Create role. Then EC2 → select the instance → Actions → Security → Modify IAM role → web-s3-role → Update IAM role. Verify on the instance:

aws sts get-caller-identity      # Arn: ...:assumed-role/web-s3-role/i-0123...
aws configure list               # credential type: iam-role
aws s3 ls s3://my-site-backups/

AWS CLI to attach: aws ec2 associate-iam-instance-profile --instance-id i-0123456789abcdef0 --iam-instance-profile Name=web-s3-role

What do I need before attaching an IAM role?

  • An EC2 instance with SSH access — see How to Launch an EC2 Instance and How to SSH into EC2. Amazon Linux 2023 comes with the AWS CLI installed.
  • An AWS user that may create IAM roles and change EC2 instances (for example an administrator in your own lab account).
  • A clear idea of what the server must do, for example "upload backups to the bucket my-site-backups". That decides the policy.

How does an IAM role give EC2 its credentials?

How an IAM role gives EC2 temporary credentials An IAM role is attached to the EC2 instance. When the AWS CLI runs aws s3 ls, it gets temporary credentials from the instance metadata service at 169.254.169.254, which AWS rotates automatically. It then calls Amazon S3 with them and the bucket list comes back. No access keys are stored on the server. IAM role: web-s3-role EC2 instance metadata 169.254.169.254 $ aws s3 ls my-site-backups no keys on disk ✓ Amazon S3 bucket temporary credentials, rotated by AWS need creds temp keys ListBuckets 200 OK

With an IAM role attached, the AWS CLI gets temporary credentials from the instance metadata service and calls Amazon S3 with them. AWS rotates them automatically, and no access keys are stored on the server.

An IAM role is an identity with permissions but no long-term password or keys. When a role is attached to an instance (through an instance profile, which the console creates for you with the same name), AWS delivers temporary credentials to the instance through the instance metadata service at 169.254.169.254, and rotates them automatically. The AWS CLI and SDKs find them by themselves — your code needs no keys at all.

How do I attach an IAM role to an EC2 instance?

Step 1 — Create the role for EC2

IAM → Roles → Create role → Trusted entity type: AWS service → Use case: EC2 → Next.

Step 2 — Give it only the permissions it needs

Search for and tick a policy. For a quick test, AmazonS3ReadOnlyAccess works. For a real server, create your own policy that allows only the actions and the bucket it needs, for example:

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": ["s3:PutObject", "s3:GetObject"],
    "Resource": "arn:aws:s3:::my-site-backups/*"
  }]
}

Never attach AdministratorAccess to an application server: one bug in your code would hand an attacker the whole account.

Step 3 — Name and create the role

Role name: web-s3-role → check the trusted entity shows ec2.amazonaws.com → Create role.

Step 4 — Attach the role to the instance

EC2 → Instances → select the instance → Actions → Security → Modify IAM role → choose web-s3-role → Update IAM role. The instance keeps running; no stop or reboot is needed. For a new instance, pick the role at launch under Advanced details → IAM instance profile.

Step 5 — Verify on the instance

aws sts get-caller-identity
aws configure list
aws s3 ls s3://my-site-backups/         # read test (bucket name = yours)
echo test > t.txt && aws s3 cp t.txt s3://my-site-backups/t.txt   # write test (needs s3:PutObject)

get-caller-identity shows an ARN with assumed-role/web-s3-role/..., and aws configure list shows the type iam-role. The server now talks to AWS with no keys on disk! 🎉

Ravindra Bagale's Tip

Students create the role but forget to attach it to the EC2 instance – then the CLI says "Unable to locate credentials" and they rush to paste an access key into the code. Never! First run aws sts get-caller-identity: if the role doesn't show, do Actions → Security → Modify IAM role. Role = no keys, remember that.

How can I see the role credentials on the instance?

The metadata service shows the attached role. New instances require IMDSv2, which needs a token first:

TOKEN=$(curl -s -X PUT http://169.254.169.254/latest/api/token -H "X-aws-ec2-metadata-token-ttl-seconds: 60")
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/; echo

The output is the role name. You never copy these credentials anywhere — the CLI and SDKs read and refresh them for you. Keep IMDSv2 required: a plain request without a token cannot read them, which protects the role credentials from simple server-side request forgery (SSRF) bugs.

Ravindra Bagale's Tip

💡 If the CLI still uses an old access key after you attach the role, old keys are still sitting in ~/.aws/credentials. The CLI checks environment variables and config files first, and the role only after that. aws configure list should show the type iam-role. Remove the old file and deactivate that key in IAM. Don't forget!

How do I fix common IAM role errors on EC2?

Ghabru naka 😅 — read the exact message:

Symptom Likely cause Fix
Unable to locate credentials No role attached Actions → Security → Modify IAM role; then aws sts get-​caller-​identity
AccessDenied / not authorized to perform Role attached but policy does not allow the action or resource Add the exact action (e.g. s3:PutObject) and bucket ARN to the role's policy
CLI still uses an old user Keys in ~/.​aws/​credentials or environment variables aws configure list; remove the file/variables; deactivate the old key
Role not in the Modify IAM role list Role was created for another service Recreate it with trusted entity EC2
aws s3 ls works, upload fails Read-only policy Grant s3:PutObject on arn:​aws:​s3:::​bucket/*
Metadata curl returns 401 Unauthorized IMDSv2 requires a token Use the token commands above (this is good security)
aws: command not found CLI not installed (non-Amazon Linux AMI) Install AWS CLI v2 from the official AWS instructions

Got it? Create the role, give only the permissions you need, attach it with Modify IAM role, and confirm with aws sts get-caller-identity. Not a single access key on the server – that's the company standard.

Frequently asked questions

How do I attach an IAM role to a running EC2 instance?

Select the instance in the EC2 console, then Actions → Security → Modify IAM role, choose the role and click Update IAM role. No stop or reboot is needed.

Why use an IAM role instead of access keys on EC2?

A role gives short-lived credentials that AWS rotates automatically, and they never sit in a file you might leak. Long-lived access keys in code or ~/.aws/credentials are one of the most common ways cloud accounts get stolen.

How do I check that my instance is using the role?

Run aws sts get-caller-identity on the instance. The ARN should contain assumed-role/ and your role name. aws configure list shows iam-role as the credential type.

What is an instance profile?

The container that passes an IAM role to an EC2 instance. When you create a role for EC2 in the console, an instance profile with the same name is created automatically, so you just pick the role name.

Can one EC2 instance have two IAM roles?

No. An instance has one instance profile with one role at a time. Put all the permissions the instance needs into that role, or replace the role with Modify IAM role.

Why do I get "Unable to locate credentials" or AccessDenied?

Unable to locate credentials: no role is attached (or the CLI cannot reach the metadata service). AccessDenied: the role is attached but its policy does not allow that action or resource.