Roles and AWS STS
IAM Role คือ Identity ที่ไม่มี password หรือ access key ถาวร ผู้ใช้, service หรือ workload ที่ได้รับอนุญาตจะ assume role แล้วรับ temporary credentials จาก AWS STS เพื่อเรียก AWS API
ทำไม Role สำคัญ
Role ลดความจำเป็นในการแจก long-term Access Key ให้ workload เช่น EC2, Lambda, ECS หรือ CI/CD เมื่อ workload ใช้ Role ระบบจะได้รับ temporary credentials ที่มีอายุจำกัดและหมุนเวียนให้โดย AWS หรือ federation flow
Trust Policy และ Permission Policy
Role มี policy สองด้านที่ต้องเข้าใจ:
- Trust Policy: ระบุว่า Principal ใดสามารถ assume role นี้ได้
- Permission Policy: ระบุว่าเมื่อ assume role แล้ว session นี้ทำ Action อะไรกับ Resource ใดได้บ้าง
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "ec2.amazonaws.com" },
"Action": "sts:AssumeRole"
}
]
}
AWS STS และ temporary credentials
AWS Security Token Service หรือ AWS STS ออก temporary security credentials ให้กับ role session หรือ federated session Credentials เหล่านี้มีอายุจำกัดและประกอบด้วย Access Key ID, Secret Access Key และ Session Token
สำหรับ EC2, การให้ Instance เข้าถึง S3 ควรใช้ IAM Role ผ่าน Instance Profile ไม่ควรใส่ Access Key ไว้ใน User Data, environment variable ถาวร หรือ source code
Common role patterns
| Pattern | Use case | ข้อควรระวัง |
|---|---|---|
| EC2 Role | Application บน EC2 อ่าน S3 หรือเขียน CloudWatch Logs | Permission ควรเจาะจง bucket/log group |
| Cross-account Role | ให้ Account A เข้า Resource หรือ operation ใน Account B | Trust Policy ต้องระบุ Principal ถูกต้อง |
| Federated Role | ผู้ใช้ Login ผ่าน Identity Provider หรือ IAM Identity Center | Permission Set และ session duration ต้องเหมาะสม |
| OIDC Role | CI/CD เช่น GitHub Actions deploy โดยไม่เก็บ Access Key | Condition ต้องจำกัด repo/branch/environment |
Best practices
- ใช้ Role สำหรับ workload บน AWS แทน IAM User Access Key
- จำกัด Trust Policy ให้แคบที่สุด เช่น service, account, OIDC subject หรือ external ID
- แยก Role ตามหน้าที่ ไม่ใช้ Role เดียวสำหรับทุก workload
- ตรวจ CloudTrail เพื่อดูว่า Role ถูก assume โดยใครและทำ Action ใด
Review questions
- แยก Trust Policy กับ Permission Policy ได้
- อธิบาย flow AssumeRole → STS → temporary credentials ได้
- รู้ว่า EC2 ควรใช้ role ผ่าน instance profile แทนการฝัง access key
- Trust Policy ตอบคำถามอะไร?
- Temporary credentials ดีกว่า long-term Access Key อย่างไร?
- Instance Profile เกี่ยวข้องกับ EC2 Role อย่างไร?