IAM Roles and Instance Profiles
Inkwell's web server must upload cover images to S3, so its code needs AWS credentials. A developer suggests pasting their own access keys into a config file. It would work, and it would be a disaster in waiting: keys in a file leak through backups, screenshots and Git history, and they never expire. Roles solve this without any secret stored at all.
The rule
Roles are worn, not owned: assume one, get temporary keys.
An IAM role is an identity with permissions but no password and no permanent access keys. Instead, a trusted party assumes the role and receives temporary credentials from AWS STS (Security Token Service), usually valid for an hour. When they expire, you assume again.
Every role has two policies:
- A trust policy: who may assume the role.
- A permissions policy: what the role may do once assumed.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "ec2.amazonaws.com" },
"Action": "sts:AssumeRole"
}
]
}This trust policy says "EC2 instances may wear this role". Its permissions policy would allow s3:PutObject on arn:aws:s3:::inkwell-covers/*.
For EC2, the role travels in an instance profile, a small container that attaches one role to an instance. The console creates one automatically with the same name as the role. Code on the instance using an AWS SDK then finds credentials by itself, from the instance metadata service, and AWS rotates them before they expire.
Roles are used for much more than servers:
- Services such as Lambda functions wear roles in the same way.
- People assume roles to get elevated access for a while, such as an "admin" role that requires MFA.
- Other accounts can be trusted, which is how cross-account access works.