Sub topic 9
IAM roles and why they replace long-lived keys
This chapter assumes you know what an IAM user is, how an access key pair works, and how to read a JSON policy with Effect, Action, and Resource. You should also be able to run basic AWS CLI commands. Trust policies and the STS call itself get their own chapters. Here the focus is the role as a concept and why it is the better default for most access.
What a role is
An IAM role is an identity in your account that has permissions but no password and no access keys of its own. Nobody signs in as a role. A trusted principal assumes it, and AWS then issues temporary credentials for the length of a session.
A role has two policy attachments that do different jobs:
- Permissions policies say what the role can do once assumed. These are the same identity-based policies you attach to users and groups.
- A trust policy says who is allowed to assume the role. It is a resource-based policy attached to the role itself.
Both must be in place. A role with broad permissions and an empty trust policy cannot be used by anyone. A role with a permissive trust policy and no permissions policy can be assumed but cannot do anything.
Why long-lived keys are a liability
A user's access key stays valid until someone deactivates it. That creates several problems in practice:
- Leaks last. A key committed to a public repository, pasted in a chat, or left in a container image works for whoever finds it, from anywhere, until you notice and rotate it.
- Rotation is manual. Each rotation means creating a second key, updating every place that uses the first, testing, and then deleting the old one. Teams skip it.
- Keys spread. Copies end up in laptops, CI settings, and config files. You cannot easily say where a given key lives.
- Attribution is weak. Several people or services sharing one user's key all appear as that user in logs.
Role credentials remove most of this. They expire on their own, so a leaked set is useful for a limited time. Nothing needs rotating by hand, because the caller requests fresh credentials as needed. Every session also has a name, so CloudTrail shows which session made each call.
| Property | IAM user access key | Role session credentials |
|---|---|---|
| Lifetime | Until deleted or deactivated | Minutes to hours, then expire |
| Rotation | You do it | Automatic on each assumption |
| Stored where | Files, environment, CI settings | Usually fetched at runtime by the SDK |
| Identity in logs | The user | The role plus a session name |
| Revocation | Deactivate the key | Wait for expiry, or deny by session issue time |
Session duration
A role has a maximum session duration setting, from 1 hour to 12 hours, with a default of 1 hour. A caller can request a shorter or longer session up to that maximum. Role chaining, where one role session assumes another role, is limited to 1 hour regardless of the setting. Shorter sessions limit the damage window. Longer ones suit long-running jobs that cannot refresh credentials.
Who can assume a role
The trust policy names the principals. Common choices:
- An AWS service, such as
ec2.amazonaws.comorlambda.amazonaws.com. The service uses the role on your behalf, for example to give an application on an EC2 instance credentials. - Users or roles in your own account.
- Principals in another account, which is the first step of cross-account access.
- Federated identities from a SAML provider or an OpenID Connect provider. This lets people from your corporate directory, or a CI system, get access without any IAM user.
Here is the trust policy that lets the EC2 service assume a role:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "ec2.amazonaws.com" },
"Action": "sts:AssumeRole"
}
]
}The Principal element appears here because this is a resource-based policy. An identity-based permissions policy has no Principal, since the principal is whoever it is attached to.
Roles in practice
The main uses of roles replace a case where you would otherwise create a user and hand out keys:
- Applications on AWS compute. An EC2 instance, ECS task, or Lambda function gets a role. The SDK finds credentials through the instance metadata service or the container credentials endpoint and refreshes them before they expire. Your code never contains a key.
- People. Engineers sign in through an identity provider or IAM Identity Center and receive a role session. There is no per-person IAM user to manage.
- Cross-account access. A role in the account that owns the resources is assumed from another account, so you do not create users in each account.
- Elevated access. A person with everyday permissions assumes a more powerful role only when needed, optionally requiring MFA.
- Automation outside AWS. A CI system proves its identity through OIDC federation and assumes a role, instead of storing a stored key as a secret.
A role used by a person can also be tied to MFA in its trust policy. This is the cross-account form from the spine:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "AWS": "arn:aws:iam::111122223333:root" },
"Action": "sts:AssumeRole",
"Condition": {
"Bool": { "aws:MultiFactorAuthPresent": "true" }
}
}
]
}Naming the account root as principal means the account is trusted, but each identity in it still needs its own permission to call sts:AssumeRole. The trust policy alone does not grant that.
Using a role from the CLI
You can request credentials with sts assume-role and export them. Afterwards get-caller-identity shows that calls run as the role.
aws sts assume-role \
--role-arn arn:aws:iam::444455556666:role/ReadOnlyAuditor \
--role-session-name audit-session
# The response contains a Credentials object. Export its values:
export AWS_ACCESS_KEY_ID=<AccessKeyId from the response>
export AWS_SECRET_ACCESS_KEY=<SecretAccessKey from the response>
export AWS_SESSION_TOKEN=<SessionToken from the response>
aws sts get-caller-identityThe session token is required. Calls that carry the key and secret but omit AWS_SESSION_TOKEN fail with an invalid security token error. The returned ARN has the form arn:aws:sts::444455556666:assumed-role/ReadOnlyAuditor/audit-session. That is an assumed-role ARN, not the role ARN, and you must remember the difference when writing policies that match on principal.
For daily use, a named profile with role_arn and source_profile in ~/.aws/config lets the CLI assume and refresh the role for you, so you avoid exporting variables by hand.
Common errors and gotchas
- AccessDenied on AssumeRole. Two checks apply. The trust policy must trust the caller, and when the caller is in another account, the caller's own identity-based policy must also allow
sts:AssumeRoleon that role. In the same account, either the trust policy naming the specific principal or an identity policy can suffice, but a trust policy naming only the account root also needs the identity policy. - Role ARN versus session ARN. Resource policies that name a role ARN match sessions of that role. A policy naming a specific session ARN matches only that session.
- Instance profile confusion. EC2 attaches an instance profile, which is a container holding one role. The console creates it for you, but the CLI and CloudFormation make it a separate object.
- Permissions do not carry over. When you assume a role, you give up the original identity's permissions for that session. You cannot use both at once.
- Existing sessions outlive policy edits. Changing a permissions policy takes effect for active sessions quickly, but the credentials themselves stay valid until expiry. To cut off a session, attach a deny policy conditioned on
aws:TokenIssueTime, which the console's revoke-sessions action does for you. - Long-lived keys still have a place. Some third-party tools cannot use roles. Use IAM Roles Anywhere, or if you must use a key, scope it tightly, rotate it, and monitor it.
Exercise
A Lambda function needs to read one S3 bucket. A teammate proposes creating an IAM user, generating an access key, and storing it in the function's environment variables. Describe the role-based alternative and name two problems it avoids.
Show answer
Create a role whose trust policy lets lambda.amazonaws.com assume it, and attach a permissions policy allowing s3:ListBucket on the bucket ARN and s3:GetObject on the bucket ARN with /*. Set that role as the function's execution role. Lambda assumes it and the SDK picks up temporary credentials automatically. This avoids a stored secret that can leak from environment variables or logs, and it avoids manual rotation, since the credentials expire and are reissued on their own. CloudTrail also records calls under the role's session name instead of a shared user.
Exercise
You run aws sts get-caller-identity after assuming a role and see an ARN containing assumed-role. A colleague says the permissions of your original user still apply. Is that correct?
Show answer
No. While the role session is active, requests are evaluated against the role's permissions (and any session policy), not those of the original identity. To use the original permissions again, stop using the exported role credentials.