Introduction
IAM Role is assigned to EC2 for AWS API access; no access key stored on disk. Instance Profile is the EC2 attachment for the role.
Instance Metadata Service (IMDS) at 169.254.169.254 provides instance info and temporary credentials.
IMDSv2 is session-oriented and more secure against SSRF attacks.
IAM Role and Instance Profile
Create role, attach required policy (e.g. S3 read), create instance profile, attach role, select profile at launch.
Principle of least privilege: only required actions and resources.
aws iam create-role --role-name ec2-s3-read \
--assume-role-policy-document file://trust-ec2.json
aws iam attach-role-policy --role-name ec2-s3-read \
--policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccessIMDSv2 Configuration
MetadataOptions HttpTokens=required in launch template enforces IMDSv2. HttpPutResponseHopLimit=1 prevents metadata leak outside container.
IMDSv1 should be disabled; security best practice.
aws ec2 modify-instance-metadata-options \
--instance-id i-xxx \
--http-tokens required \
--http-put-response-hop-limit 1Using Metadata
Get token with curl, then request metadata endpoint. Instance ID, AZ, role credentials readable.
SDK (boto3) uses automatic credential chain; reads from metadata if role exists.
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" \
-H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
curl -H "X-aws-ec2-metadata-token: $TOKEN" \
http://169.254.169.254/latest/meta-data/iam/security-credentials/Security Risks
SSRF vulnerability can leak IMDS credentials. IMDSv2 requires token. Hop limit critical in container environments.
Avoid broad permissions like s3:* in role policy.
Tüm yeni instance'larda HttpTokens=required varsayılan yapın.
Audit and Compliance
IAM Access Analyzer finds unused roles. CloudTrail logs API calls.
Prefer function-based roles (app role, backup role) over per-instance role.
- IMDSv2 zorunlu
- Least privilege policy
- Instance profile kullanın
- Access key EC2'de saklamayın
- CloudTrail izleme
Conclusion
IAM Role + Instance Profile is the foundation of EC2 security. Enable IMDSv2, apply least privilege, do not use access keys.
Limit metadata access with container hop limit.