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.
The shortcut
Whenever something needs AWS access, ask "Is it a person at a keyboard?" If not, it gets a role, never access keys. Then write two sentences: who may wear it (trust) and what it may do (permissions).
A person at a keyboard?
No, it is a server. So: a role,
inkwell-web-role.
The trap is fixing an "access denied" error by loosening the wrong policy. If an instance cannot assume a role, check the trust policy; if it assumed the role but cannot act, check the permissions policy.
Drills
Answer fast — trust the rule.
What kind of credentials does assuming a role give you?
Which policy of a role decides who may assume it?
How does an EC2 instance receive an IAM role?
A Lambda function needs to read a DynamoDB table. What should it use?
Remember
- Roles are worn, not owned: assume one, get temporary credentials.
- Two policies: trust (who may wear it) and permissions (what it may do); EC2 wears it through an instance profile.
- Trap: never paste access keys onto servers; if assuming fails, check trust, if acting fails, check permissions.
