Interview Q&A / AWS & Cloud

BeginnerQuick answer1 min readUpdated 3 Oct 2026

Why use an IAM role for an EC2 instance instead of storing access keys on it?

SHORT ANSWER

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

python
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.com assume 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.

#aws#iam#ec2#security

Related questions

Practise more AWS & Cloud questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open AWS & Cloud quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.