Why You Need IAM Roles
Managing static AWS access keys on EC2 instances poses several operational and security challenges:- Securely provisioning credentials to every new instance.
- Rotating keys when they expire or are compromised.
- Preventing API request failures due to missing or revoked keys.

Instances with IAM roles receive short-lived credentials from the metadata service. This eliminates the need to store access keys on disk.
What Is an IAM Role?
An IAM role is an AWS identity with attached permissions defined by IAM policies. Unlike an IAM user, a role:- Isn’t tied to a specific individual.
- Has no long-term credentials (no static keys or passwords).
- Can be assumed by authorized entities (EC2, Lambda, ECS, etc.).

EC2 Instance Metadata Service
EC2 instance metadata provides instance information and temporary credentials at a fixed IP address. To list all metadata categories:- ami-id/
- instance-id/
- iam/
- instance-action/
Enable and enforce IMDSv2 on your instances to protect against SSRF attacks. See AWS IMDSv2 documentation.
Retrieving Temporary Credentials
Assuming your role is nameds3access, fetch credentials with:
Using AWS CLI with IAM Roles
With the IAM role attached, the AWS CLI handles credential retrieval and signing transparently. For example, list an S3 bucket:- CLI requests temporary credentials from the metadata service.
- It uses those credentials to sign API calls.
- Results (e.g., bucket contents) are returned.

Best Practices
| Practice | Recommendation |
|---|---|
| Use IAM Roles | Avoid embedding keys; assign minimal privileges to roles. |
| Enforce IMDSv2 | Require session tokens and mitigate SSRF risks. |
| Rotate Policies | Update IAM policies regularly to follow least-privilege principles. |
| Monitor with CloudTrail | Track IAM role assumptions and API calls for auditing and compliance. |
Summary
- IAM roles provide temporary, auto-rotated credentials scoped to your EC2 instances.
- A single EC2 instance can hold one IAM role, while a role can attach to multiple instances.
- AWS SDKs, CLI, and tools automatically retrieve metadata credentials without manual intervention.
