Why use an IAM role for an EC2 instance instead of storing access keys on it?
A role gives the instance temporary credentials that AWS rotates automatically, so no long-lived secret sits on disk or in code. Access keys can leak through code repos, images or logs and stay valid until someone revokes them.
Explain it simply
Access keys are like a photocopied master key left under the doormat. A role is a smart card that the security desk issues fresh every few hours to a guard who is on duty. If someone steals the card, it soon stops working.
Example
import boto3
# No keys in code. On an EC2 instance with an instance profile,
# the SDK finds temporary credentials automatically.
s3 = boto3.client("s3")
for bucket in s3.list_buckets()["Buckets"]:
print(bucket["Name"])How it works:
- You create an IAM role with a trust policy that lets
ec2.amazonaws.comassume it, and attach permissions. - An instance profile carries that role to the instance.
- The SDK or CLI reads temporary credentials from the instance metadata service and refreshes them before they expire.
The same idea applies to Lambda execution roles, ECS task roles and EKS service accounts: give the workload a role, never a key.
If a leaked key is ever found, deactivate it in IAM at once, review CloudTrail for what it did, then create a replacement only if truly needed.
What to say in the interview
"Roles give workloads short-lived credentials that rotate automatically, so there is nothing to leak or manage. I attach a least-privilege role through an instance profile, and I do the same with Lambda execution roles and ECS task roles."
Common mistakes
- Committing access keys to a public GitHub repo.
- Using the root user's keys for applications.