Let's think about this for a second
An IAM User authenticates with an access key (a long-term credential) — if that's hardcoded in your code, there's a leak risk. An IAM Role, on the other hand, lets an AWS resource (an EC2 instance, a Lambda function) 'assume' it and automatically obtain temporary credentials (which auto-rotate) — you never have to write an access key in your code at all. Attach a Role (say, S3ReadOnlyRole) to an EC2 instance, and the application inside can access S3 without any access key — the AWS SDK auto-fetches temporary credentials from the instance metadata.
Let's connect this to a real scenario
If an application on an EC2 instance needs to read an S3 bucket — instead of writing an access key into a config file, attach the 'S3ReadOnlyRole' IAM Role to the instance, and the AWS SDK in your application code will automatically fetch temporary credentials and connect to S3 — with zero credentials written in your code, there's no leak risk at all.
Let's look at this together
# Create a role EC2 can assume, attach S3 read-only policy
aws iam create-role \
--role-name S3ReadOnlyRole \
--assume-role-policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}'
aws iam attach-role-policy \
--role-name S3ReadOnlyRole \
--policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
# Attach the role to a running EC2 instance
aws ec2 associate-iam-instance-profile \
--instance-id i-0123456789abcdef0 \
--iam-instance-profile Name=S3ReadOnlyRole$ (from inside the EC2 instance) aws s3 ls
# Works with zero configured credentials — the role provides themTry it in 5 minutes
Create an IAM Role (S3 read-only) and try attaching it to an EC2 instance — run `aws s3 ls` from inside the instance and confirm it works without any access key configured.
A quick word of caution
Once an IAM Role is attached to an EC2 instance, every application/user running on that instance can share that Role's permissions — be careful with Role permissions on multi-tenant instances.