SkillSprout
Chapter 3 · Lesson 3
Intermediate
8 min read

Roles

Overview

An IAM role is an identity with permissions that is assumed by someone or something that needs it temporarily. Unlike a user, a role has no permanent password or access keys. When an entity assumes a role, the AWS Security Token Service (STS) returns temporary credentials (access key, secret and session token) that expire automatically.

Roles solve the biggest security problem in cloud projects: how can an application running on EC2, Lambda or ECS call AWS without hard-coded secrets? You attach a role to the compute resource and the SDK retrieves rotating credentials automatically. Roles are also how you give access across AWS accounts, to federated corporate users, mobile users and third-party vendors.

A role has two policy parts: a trust policy (who may assume it) and permission policies (what it may do once assumed). Both questions appear constantly on the SAA-C03 exam.

Key Concepts

  • A role has no long-term credentials; assuming it returns temporary STS credentials that expire.
  • Trust policy (resource-based) defines who can assume the role (the Principal); permissions policies define what the role can do.
  • Session duration: 1 hour by default; configurable 1–12 hours for the role; role chaining is limited to 1 hour.
  • EC2 instance profile is the container that passes a role to an instance; the SDK reads credentials from the instance metadata service (IMDSv2 recommended).
  • Service roles let AWS services act for you (Lambda execution role, ECS task role); service-linked roles are predefined by the service and cannot be edited.
  • Cross-account access: create a role in the target account that trusts the source account; use an External ID for third parties (confused-deputy protection).
  • Federation: SAML 2.0, OIDC / web identity (via IAM OIDC providers or Cognito) and IAM Identity Center map external identities to roles.
  • iam:PassRole is required to hand a role to a service; restrict it to prevent privilege escalation.
  • By default up to 1,000 roles per account (adjustable); trust policy default size limit 2,048 characters.

Detailed Notes

Anatomy of a role

Every role consists of:

  1. Trust policy — a JSON document stating which principals may call sts:AssumeRole (or related actions).
  2. Permission policies — managed and/or inline policies defining allowed actions.
  3. Optional permissions boundary and maximum session duration.

Trust policy: let EC2 assume the role

json
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "Service": "ec2.amazonaws.com" },
    "Action": "sts:AssumeRole"
  }]
}

Trust policy: cross-account access with External ID

json
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "AWS": "arn:aws:iam::444455556666:root" },
    "Action": "sts:AssumeRole",
    "Condition": {
      "StringEquals": { "sts:ExternalId": "Vendor-9f3b2c" },
      "Bool": { "aws:MultiFactorAuthPresent": "true" }
    }
  }]
}

For cross-account access the caller also needs an identity policy allowing sts:AssumeRole on the role ARN (unless the trust policy names a specific user/role ARN in the same account).

How assuming a role works

text
1. Principal calls sts:AssumeRole (RoleArn, RoleSessionName)
2. STS checks the TRUST policy of the role
3. STS returns temporary credentials: AccessKeyId (ASIA...), SecretAccessKey, SessionToken, Expiration
4. Principal signs API calls with those credentials; permissions = role's policies
bash
aws sts assume-role \
  --role-arn arn:aws:iam::111122223333:role/ReadOnlyAuditor \
  --role-session-name audit-2025 \
  --duration-seconds 3600
python
import boto3

# On EC2/Lambda/ECS no keys are needed - the role credentials are picked up automatically
s3 = boto3.client("s3")
print([b["Name"] for b in s3.list_buckets()["Buckets"]])

Types of roles and common use cases

Use caseWho/what assumes the roleNotes
EC2 access to AWSEC2 via instance profileCredentials rotate automatically via instance metadata
Lambda execution roleLambda serviceNeeds logs permissions + whatever the function calls
ECS/EKS tasksTask role / IAM Roles for Service Accounts (IRSA) / Pod IdentityLeast privilege per task or pod
Cross-account accessIAM users/roles in another accountTrust policy names the other account
Workforce SSOIAM Identity Center / SAML IdPFederated users assume roles
Web / mobile usersCognito identity pools, OIDCTemporary credentials for S3/DynamoDB access
CI/CD (GitHub Actions)OIDC provider trustNo stored access keys
On-premises workloadsIAM Roles AnywhereX.509 certificates exchange for temporary credentials
Service-linked rolesThe AWS service itselfe.g. AWSServiceRoleForAutoScaling; managed by AWS

Session limits you need to know

ItemValue
Default session duration (AssumeRole)1 hour (min 15 minutes, max 12 hours subject to the role's maximum setting)
Role chaining (role assumes another role)Max 1 hour per session
Console role switchingUp to the role's maximum session duration
Temporary credential prefixASIA

Roles vs. users vs. resource-based policies

IAM userIAM roleResource-based policy
CredentialsLong-termTemporaryNone
Cross-accountNeeds user per account or roleYesYes (grants directly to principal)
When principal uses a role, does it keep original permissions?n/aNo — it gives up its original permissions while the role is assumedYes — keeps its own permissions plus the resource grant

This last point is subtle and tested: with a resource-based policy (S3 bucket, SQS, SNS, KMS) a principal from another account can access the resource directly while retaining its original permissions.

PassRole and privilege escalation

To launch an EC2 instance with a role or create a Lambda with an execution role, the caller needs iam:PassRole for that role. Without a restriction, a developer could pass an admin role to a function they control. Limit it:

json
{
  "Effect": "Allow",
  "Action": "iam:PassRole",
  "Resource": "arn:aws:iam::111122223333:role/app-*",
  "Condition": { "StringEquals": { "iam:PassedToService": "lambda.amazonaws.com" } }
}

Securing EC2 role credentials

Use IMDSv2 (session-oriented token requests) to mitigate SSRF theft of role credentials; enforce it with HttpTokens=required.

bash
aws ec2 modify-instance-metadata-options --instance-id i-0abc123 \
  --http-tokens required --http-endpoint enabled

Real World Example

Scenario — a media company with separate dev, prod and security accounts.

A media company stores video masters in S3 in a production account and runs transcoding workers in a processing account. Previously a developer had created an IAM user in production and pasted its keys into the worker AMI.

The team replaces this with roles. In the production account they create VideoMasterReader, whose trust policy names the processing account's TranscoderInstanceRole, and whose permission policy allows s3:GetObject on the masters bucket only. The EC2 workers have an instance profile with TranscoderInstanceRole, which is permitted to call sts:AssumeRole on VideoMasterReader. The AWS SDK assumes it automatically and refreshes credentials before expiry — no secret ever exists on disk.

An external subtitle vendor receives a separate role with an External ID and read access to only the subtitle prefix. When the vendor contract ends, the team deletes the role and all access disappears at once. CloudTrail shows each session name, so audits can tie every action to a specific job.

Architecture Diagram

EC2 instance assuming a role to reach S3
Architecture
AWS Cloud
Region
VPC
Private subnet
EC2 appinstance profile
IAM roletrust: ec2.amazonaws.com
Permissions policys3:GetObject
S3 bucket

The instance profile hands temporary STS credentials to the application, so no access keys are stored.

  1. 1The EC2 instance is launched with an instance profile containing the IAM role.
  2. 2The SDK requests role credentials from the instance metadata service (IMDSv2); STS issues temporary keys.
  3. 3The application signs S3 requests with those credentials; IAM evaluates the role's permissions policy.
  4. 4Credentials expire and are renewed automatically, so there is nothing to rotate manually.

Best Practices

  • ✓Use roles for every workload (EC2, Lambda, ECS, EKS) instead of access keys stored in code, AMIs or environment files.
  • ✓Scope trust policies tightly: name specific roles/accounts, add ExternalId for third parties and aws:PrincipalOrgID for in-organisation access.
  • ✓Give each application its own role with least-privilege permissions; avoid sharing one broad role.
  • ✓Restrict iam:PassRole to specific role ARNs and services to block privilege escalation.
  • ✓Set maximum session durations as short as practical and rely on session tags or session names for audit trails.
  • ✓Require IMDSv2 on EC2 and block unnecessary access to the metadata endpoint from containers.
  • ✓Use permission boundaries when delegating role creation to developers.
  • ✓Federate workforce users (Identity Center/SAML) into roles rather than creating IAM users per account.

Common Interview Questions

Exam Tips

SAA-C03 focus

  • "Application on EC2 / Lambda / ECS needs to call AWS" -> attach an IAM role (instance profile for EC2). Never embed access keys.
  • Cross-account access -> role in the target account trusting the source account; caller uses STS AssumeRole. Third parties add External ID.
  • Remember the session numbers: default 1 hour, max 12 hours, role chaining = 1 hour.
  • Trust policy = who; permission policy = what. A trust-policy question will show sts:AssumeRole.
  • When you assume a role you give up your original permissions; with a resource-based policy you keep them.
  • "Web/mobile app users need temporary AWS access" -> Cognito identity pool; "corporate users with SAML" -> SAML federation / Identity Center.
  • "On-premises server needs temporary AWS credentials" -> IAM Roles Anywhere.
  • Compromised instance credentials? Revoke by attaching a deny-before-time policy (Revoke active sessions) to the role.

Finished this lesson?

0 of 64 lessons done · 0% of the course