Engineering

IAM roles: AWS access without long-lived keys

How IAM roles hand out temporary credentials, and how people, EC2, Lambda and a GitLab CI pipeline use them so there are no access keys to leak.

At the end of the last post, a contractor could deploy one website and nothing else. That part worked. The weak point was how they signed in: an access key that never expires, sitting on a laptop you don't control. If it leaks, it works for whoever finds it until someone notices.

This is the last of three posts on AWS Identity and Access Management (IAM) that I'm writing while studying for the AWS Solutions Architect Associate exam. It covers roles, the way AWS hands out credentials that expire on their own. By the end:

  • The contractor's permissions live on a role that hands out one-hour credentials.
  • You'll know how EC2 and Lambda get credentials without anyone storing a key.
  • You'll see how a site's GitLab pipeline deploys to AWS with no AWS secrets stored in GitLab at all.

What a role is

A role is an identity with permissions, like a user, but with no password and no access keys of its own. Instead, someone or something assumes it, and AWS Security Token Service (STS) gives them temporary credentials:

  • An access key ID starting with ASIA (long-lived user keys start with AKIA).
  • A secret access key.
  • A session token, which has to be sent with every request.
  • An expiry time, from 15 minutes up to the role's maximum session duration (1 hour by default, up to 12).

When they expire, they stop working. Nobody has to remember to rotate or delete them.

Two policies on every role

A role has two separate policies, and they answer different questions:

Policy Question it answers Example
Trust policy Who may assume this role? "Users in account 111122223333", "the Lambda service", "GitLab jobs on the main branch of one project"
Permissions policy What can they do once they've assumed it? The deploy-example-site policy from the last post

The trust policy is a resource-based policy, with the role as the resource, so it has a Principal. The permissions policies are ordinary identity-based policies, the same managed or inline policies you attach to users and groups.

Both sides have to agree. When a trust policy trusts a whole account, as the one below does, the caller also needs its own policy allowing sts:AssumeRole on that role. If either side says no, the request fails. (A trust policy that names one specific user or role ARN is enough on its own within the same account, but trusting the account and controlling access with ordinary IAM policies is easier to manage.)

Demo: move the contractor's permissions onto a role

This builds on the deploy-example-site policy from the last post. If you've cleaned that up, create it again from step 1 of that demo. Replace 111122223333 with your account ID and example-site-bucket with the bucket you created.

Step 1: Write the trust policy

Save this as trust-policy.json:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "AWS": "arn:aws:iam::111122223333:root" },
      "Action": "sts:AssumeRole"
    }
  ]
}

The :root in that principal looks alarming after the first post, but here it doesn't mean the root user. It means "this account": any user or role in account 111122223333 whose own policies allow sts:AssumeRole on this role. The account decides who that is with ordinary IAM policies.

Step 2: Create the role and attach the permissions

aws iam create-role --role-name site-deployer \
  --assume-role-policy-document file://trust-policy.json

Don't forget to create the deploy-example-site policy from the last post otherwise the command below will not be able to attach it to your contractor.

aws iam attach-role-policy --role-name site-deployer \
  --policy-arn arn:aws:iam::111122223333:policy/deploy-example-site

Step 3: Assume it by hand

From your admin profile, which already allows sts:AssumeRole:

aws sts assume-role \
  --role-arn arn:aws:iam::111122223333:role/site-deployer \
  --role-session-name test --duration-seconds 900
{
    "Credentials": {
        "AccessKeyId": "ASIAEXAMPLEEXAMPLE",
        "SecretAccessKey": "…",
        "SessionToken": "…",
        "Expiration": "2026-12-04T15:42:10+00:00"
    },
    "AssumedRoleUser": {
        "AssumedRoleId": "AROAEXAMPLEEXAMPLE:test",
        "Arn": "arn:aws:sts::111122223333:assumed-role/site-deployer/test"
    }
}

Those credentials stop working 15 minutes from now. The session name, test, appears in the ARN and in CloudTrail, so give each person or job its own and you can tell sessions apart.

Step 4: Let the CLI do it for you

Copying three values out of JSON gets old quickly. Add a profile to ~/.aws/config and the CLI assumes the role, caches the credentials, and renews them when they expire:

[profile site-deployer]
role_arn = arn:aws:iam::111122223333:role/site-deployer
source_profile = admin

source_profile is the profile whose credentials are used to call AssumeRole. Then:

aws sts get-caller-identity --profile site-deployer
# "Arn": "arn:aws:sts::111122223333:assumed-role/site-deployer/botocore-session-1764860530"

aws s3 sync site/ s3://example-site-bucket/ --delete --profile site-deployer
# upload: site/index.html to s3://example-site-bucket/index.html

aws s3 ls --profile site-deployer
# An error occurred (AccessDenied) when calling the ListBuckets operation

Same permissions as the contractor user in the last post, but nothing stored anywhere lasts longer than an hour.

Where the contractor fits in

In the real version, the contractor doesn't get a user in your account at all. You change the trust policy's principal to their account, arn:aws:iam::444455556666:root, and they let their own IAM Identity Center user assume your role. They sign in with their own MFA, you never issue a credential, and when the work ends you delete the role. The access is gone and there's nothing to collect back.

This is cross-account access, and it's the pattern the exam expects whenever one account needs to reach into another.

Clean up

aws iam detach-role-policy --role-name site-deployer \
  --policy-arn arn:aws:iam::111122223333:policy/deploy-example-site
aws iam delete-role --role-name site-deployer

Delete the [profile site-deployer] block from ~/.aws/config, and the policy too if you're done with it, as in the last post.

Roles for AWS services

The same idea gets rid of keys inside AWS as well. The trust policy names a service as the principal, and the service assumes the role for your code.

Lambda: the execution role

Every Lambda function has an execution role. This is could be the trust policy on a site's contact form:

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

Its permissions policy lists exactly what the function needs: send email from one address through SES, write submissions to one DynamoDB table, read one Parameter Store secret, and write its own logs. Lambda assumes the role on every invocation, and the AWS SDK in the function finds the credentials in environment variables on its own. The function's code has no keys in it and no configuration for them.

EC2: instance profiles

EC2 works the same way with one extra wrapper, the instance profile, which is a container that attaches one role to an instance. The console creates it for you when you pick a role; with the CLI it's two more commands, create-instance-profile and add-role-to-instance-profile.

Code on the instance gets credentials from the instance metadata service, and the SDKs and CLI do this automatically. To see what they see:

TOKEN=$(curl -sX PUT http://169.254.169.254/latest/api/token \
  -H "X-aws-ec2-metadata-token-ttl-seconds: 300")
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" \
  http://169.254.169.254/latest/meta-data/iam/security-credentials/

That first request is IMDSv2, which requires a session token before it returns anything. Require IMDSv2 on every instance. It blocks a class of attacks where a vulnerable web app is tricked into fetching that URL and handing the role's credentials to an attacker.

Roles for CI: GitLab with OIDC

CI pipelines are where long-lived keys most often end up: pasted into a CI variable, available to every job and every maintainer, and never rotated. A site's pipeline doesn't have to have any. Instead:

  1. GitLab signs a short-lived OpenID Connect (OIDC) token for each job, saying which project, branch and job it is.
  2. The job sends that token to STS with AssumeRoleWithWebIdentity.
  3. STS verifies the token's signature with GitLab's published keys (the AWS account registers GitLab as an OIDC identity provider), checks the role's trust policy, and returns temporary credentials.

The trust policy is where the security lives. This one only lets jobs on the main branch of one project assume the deploy role:

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "Federated": "arn:aws:iam::111122223333:oidc-provider/gitlab.com" },
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
      "StringEquals": { "gitlab.com:aud": "https://gitlab.com" },
      "StringLike":   { "gitlab.com:sub": "project_path:my-group/my-site:ref_type:branch:ref:main" }
    }
  }]
}

Leave out the sub condition and any project on gitlab.com could assume your role. It's the first thing to check in any OIDC trust policy.

On the GitLab side, the job asks for a token, and the AWS CLI does the rest when it sees these environment variables:

deploy:
  id_tokens:
    GITLAB_OIDC_TOKEN:
      aud: https://gitlab.com
  variables:
    AWS_ROLE_ARN: arn:aws:iam::111122223333:role/my-site-ci-deploy
    AWS_ROLE_SESSION_NAME: gitlab-$CI_JOB_ID
  script:
    - echo "$GITLAB_OIDC_TOKEN" > /tmp/web_identity_token
    - export AWS_WEB_IDENTITY_TOKEN_FILE=/tmp/web_identity_token
    - aws s3 sync site/ s3://example-site-bucket/ --delete

This site has two such roles. The plan role trusts any branch of the project and can only read (apart from the Terraform state lock file), so merge request pipelines can run terraform plan. The deploy role can change things and only trusts main. A malicious merge request can't deploy anything, because its jobs can't get the deploy role.

GitHub Actions works the same way, with token.actions.githubusercontent.com as the provider.

iam:PassRole

One more permission comes up as soon as roles are involved. When you create a Lambda function or launch an EC2 instance with a role, you're passing that role to the service. That needs iam:PassRole on the role.

It exists to stop privilege escalation. Without it, someone allowed to create Lambda functions could attach an admin role to their function and do through it anything that role can do. Limit iam:PassRole to specific role ARNs, never "Resource": "*". A site's deploy role can only pass roles whose names are specified.

On the exam

  • Applications on EC2 use an instance profile with a role. "Store access keys on the instance" is never the right answer.
  • Lambda functions get permissions from their execution role.
  • Cross-account access: create a role in the target account that trusts the other account, and have the other account's users assume it.
  • A third party, such as a monitoring vendor, assumes your role with an external ID in the trust policy's conditions. It prevents the "confused deputy" problem, where another of the vendor's customers tricks the vendor into using your role.
  • Web or mobile users signing in through Google, Facebook or similar: Amazon Cognito identity pools, which use AssumeRoleWithWebIdentity behind the scenes.
  • Corporate directory sign-in: IAM Identity Center or SAML 2.0 federation.
  • Trust policy = who can assume. Permissions policy = what they can do. Both are needed.
  • Role sessions last 15 minutes to 12 hours. Chaining from one role into another caps the session at 1 hour.

Checklist

  • Every EC2 instance and Lambda function gets its permissions from a role, with no keys in code, environment variables or AMIs.
  • Instances require IMDSv2.
  • CI pipelines assume roles with OIDC, and each trust policy has a sub condition naming the project and branch.
  • Outside people and accounts get a role to assume, not a user in your account.
  • iam:PassRole is limited to specific role ARNs.
  • The credential report from the first post shows no access keys that a role could replace.

Wrapping up the series

Across the three posts, the account went from a root profile on my laptop to this:

  1. Lock down a new AWS account: root has MFA and no keys, and day-to-day work happens as an Identity Center admin.
  2. IAM users, groups and policies: least-privilege policies, attached to groups, tested with the policy simulator.
  3. This post: those same policies on roles, so the credentials that people, services and pipelines use expire on their own.

If I had to keep one idea from all of it: grant the specific actions on the specific resources, through credentials that expire. Everything else in IAM is a variation on that.

Need something like this built?

WAKO Digital designs, builds and runs software like this for clients. Describe the problem and I'll reply within one to two business days.

Start a project