Explain it simply
OIDC, simply
Think of an access key as a real key to the office. Copy one for your CI system and that key never expires, and anyone who copies it can walk in at any time.
OIDC works like a visitor badge system. For every workflow run, GitHub issues a small signed ID card (a token) that says 'this job is running from the main branch of the acme/orders-service repo'. AWS checks the card and, if it matches, hands out a temporary badge (temporary credentials) that lasts about an hour. There is no stored key any more, so there is nothing to steal.
Problem → Why → Solution
Access keys sitting in repository secrets
The easiest way to deploy to AWS from CI is to create an IAM user, generate an access key and store AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY as repository secrets. It works — but the key never expires, someone has to remember to rotate it, and because it deploys, its permissions tend to be broad.
There are many ways for the key to leak: a debug step prints it into the workflow log, a compromised third-party action ships environment variables to an attacker, it travels along when a repo is forked or copied, or it lingers on a former employee's laptop. Once leaked, it works from anywhere in the world until someone revokes it.
# The old way: a long-lived IAM user key stored as repository secrets
name: deploy-old
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} # never expires
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} # exposed to every step
AWS_DEFAULT_REGION: us-east-1
steps:
- uses: actions/checkout@v4
- run: npm ci && npx cdk deploy --all --require-approval neverWhy this is a risk
A long-lived credential proves only what you hold, not who you are: anyone holding the key — the workflow or an attacker — looks identical. With OIDC, credentials are minted per run, AWS checks the repo, branch and environment in the trust policy, and the credentials expire within minutes to hours.
From token to temporary credentials
GitHub Actions is an OpenID Connect (OIDC) identity provider. When a job has the id-token: write permission, the runner can request a JSON Web Token (JWT) from https://token.actions.githubusercontent.com. GitHub signs the token, and it carries claims: iss (the issuer), aud (the audience — sts.amazonaws.com for AWS), sub (which repo and which branch, environment or event), plus details such as repository, ref and run_id.
- sub claim
- The token's subject: a string describing where this run came from. Examples: repo:acme/orders-service:ref:refs/heads/main (a branch push), repo:acme/orders-service:environment:production (a job that uses an environment), repo:acme/orders-service:pull_request (a PR). Most of the trust policy's security depends on checking this string strictly.
On the AWS side you create an IAM OIDC identity provider once per account, which says 'I trust tokens signed by token.actions.githubusercontent.com'. Then you create an IAM role whose trust policy names that provider as a Federated principal with the action sts:AssumeRoleWithWebIdentity. Two conditions matter most: token.actions.githubusercontent.com:aud must equal sts.amazonaws.com, and token.actions.githubusercontent.com:sub must equal your exact repo and branch or environment.
In the workflow, the aws-actions/configure-aws-credentials action requests the token and calls STS AssumeRoleWithWebIdentity. STS verifies the token's signature, expiry and the conditions, then returns a temporary access key, secret and session token. The action exports them as environment variables for later steps, so the aws CLI and cdk deploy work as usual. Nothing secret is stored in the repository.
Notice what has disappeared: there is no IAM user and no secret in GitHub. The JWT itself expires within minutes and is useful only for its audience, and the AWS credentials last one hour by default, capped by the role's maximum session duration. A leaked log line is worth almost nothing to an attacker an hour later.
GITHUB ACTIONS OIDC TO AWS
--------------------------
GitHub Actions runner AWS account 111122223333
+------------------------+ 1. request JWT +---------------------------+
| job (id-token: write) | ----------------> | GitHub OIDC issuer |
| | <---------------- | token.actions.github... |
| | 2. signed token +---------------------------+
| | (sub = repo + branch or environment)
| |
| | 3. AssumeRoleWithWebIdentity(token, role ARN)
| | ----------------> +---------------------------+
| | | AWS STS |
| | | - signature via IAM OIDC |
| | | identity provider |
| | | - trust policy aud + sub |
| | <---------------- +---------------------------+
| aws / cdk deploy | 4. temporary credentials (about 1 hour)
+------------------------+- Job asks GitHub for a signed JWT
- Action calls AssumeRoleWithWebIdentity
- STS checks aud and sub conditions
- Short-lived credentials for this run
The sub condition in the trust policy is the real security gate. Without it, a workflow in any repository on GitHub could try to assume your role.
A trust policy pinned to repo and environment
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "GitHubActionsProductionDeploy",
"Effect": "Allow",
"Principal": {
"Federated":
"arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
"token.actions.githubusercontent.com:sub":
"repo:acme/orders-service:environment:production"
}
}
}
]
}The principal is the GitHub OIDC provider in your account, and the action is sts:AssumeRoleWithWebIdentity. StringEquals pins aud to sts.amazonaws.com and sub to the production environment of the acme/orders-service repo exactly. To allow only pushes to one branch instead, set sub to repo:acme/orders-service:ref:refs/heads/main.
A workflow that tests, waits for approval, then deploys CDK
This workflow has two jobs. The test job runs unit tests and cdk synth without any AWS credentials. The deploy job uses the production GitHub environment, so it waits until one of the environment's required reviewers approves — that is the approval gate. Only then does it assume the role through OIDC and deploy a CDK app (such as an OrdersStack in account 111122223333).
Grant id-token only where it is needed
The workflow level grants only contents: read, and id-token: write appears only inside the deploy job. Even if a dependency in the test job were compromised, it could not request an AWS token.
name: deploy-orders
on:
push:
branches: [main]
permissions:
contents: read # default for every job: read the repo, nothing else
concurrency:
group: deploy-production
cancel-in-progress: false
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- run: npm test
- run: npx cdk synth --quiet
deploy:
needs: test
runs-on: ubuntu-latest
environment: production # required reviewers = approval gate
permissions:
contents: read
id-token: write # lets this job request the OIDC token
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- name: Assume the deploy role with OIDC (no stored keys)
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::111122223333:role/github-orders-deploy
role-session-name: gha-${{ github.run_id }}
aws-region: us-east-1
- run: aws sts get-caller-identity
- run: npx cdk deploy --all --require-approval neverCode breakdown
- permissions
permissions: contents: readSets the minimum default permissions for the whole workflow. As soon as you write a permissions block, every permission you do not list becomes none.
- concurrency
group: deploy-productionStops two production deploys from running at the same time. cancel-in-progress: false avoids cutting off a CloudFormation update halfway through.
- environment: production
environment: productionApplies the GitHub environment's protection rules (required reviewers, wait timer, allowed branches) to the job. It also makes the token's sub repo:acme/orders-service:environment:production, which matches the trust policy from the syntax section.
- id-token: write
id-token: writeWithout this permission the runner cannot request an OIDC token, so the configure-aws-credentials step fails to get credentials. It grants no write access to the repository — only the right to request a token.
- configure-aws-credentials
role-to-assume / role-session-name / aws-regionRequests the token, calls AssumeRoleWithWebIdentity and exports the temporary credentials for later steps. Putting run_id in role-session-name means every API call in CloudTrail can be traced back to the exact workflow run.
- cdk deploy
npx cdk deploy --all --require-approval neverCI has no interactive prompt, so --require-approval never is used; the human approval already happened at the GitHub environment. The CDK CLI uses this role to assume the bootstrap roles and deploy.
Sample output from the deploy job (IDs will differ):
Run aws sts get-caller-identity
{
"UserId": "AROA3EXAMPLEROLEID:gha-11223344556",
"Account": "111122223333",
"Arn": "arn:aws:sts::111122223333:assumed-role/github-orders-deploy/gha-11223344556"
}
Run npx cdk deploy --all --require-approval never
OrdersStack: deploying... [1/1]
OrdersStack: creating CloudFormation changeset...
OrdersStack (no changes)- Push to main
- test job: unit tests + cdk synth
- deploy job waits for reviewer
- OIDC -> AssumeRoleWithWebIdentity
- cdk deploy via CloudFormation
Reviewer rejects
Job never gets an AWS token
sub does not match
STS: Not authorized to perform AssumeRoleWithWebIdentity
Everything matches
Stack updated, credentials expire
Setting up the AWS side: CLI and CDK
An account can have only one OIDC provider for token.actions.githubusercontent.com, but as many roles as you like, one per repo or environment. AWS now validates GitHub's certificate itself, so you no longer need to supply a thumbprint.
An important point about the role's permissions: deploying with CDK does not require giving the CI role AdministratorAccess. The CDK CLI assumes the cdk-hnb659fds-* roles created during bootstrap (deploy, file-publishing, image-publishing, lookup), and the actual resources are created by the CloudFormation execution role. So the CI role only needs permission to call sts:AssumeRole on those roles.
# 1. Trust GitHub's OIDC issuer (once per account)
aws iam create-open-id-connect-provider \
--url https://token.actions.githubusercontent.com \
--client-id-list sts.amazonaws.com
# 2. The deploy role, trusted only by repo + environment (trust-policy.json above)
aws iam create-role --role-name github-orders-deploy \
--assume-role-policy-document file://trust-policy.json \
--max-session-duration 3600
# 3. Its only permission: assume the CDK bootstrap roles
aws iam put-role-policy --role-name github-orders-deploy \
--policy-name assume-cdk-bootstrap-roles \
--policy-document file://assume-cdk-roles.json{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AssumeCdkBootstrapRoles",
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": "arn:aws:iam::111122223333:role/cdk-hnb659fds-*"
}
]
}The setup itself belongs in infrastructure as code too. The CDK app below creates the provider (OidcProviderNative, which uses the native AWS::IAM::OIDCProvider resource), the role with its trust conditions, and permission to assume the bootstrap roles. An admin has to deploy this one stack by hand before the pipeline exists — a classic chicken-and-egg step.
import { App, CfnOutput, Duration, Stack, StackProps } from "aws-cdk-lib";
import * as iam from "aws-cdk-lib/aws-iam";
import { Construct } from "constructs";
interface GitHubDeployAccessProps extends StackProps {
repo: string; // "owner/name"
environment: string; // GitHub environment allowed to deploy
}
export class GitHubDeployAccessStack extends Stack {
constructor(scope: Construct, id: string, props: GitHubDeployAccessProps) {
super(scope, id, props);
const provider = new iam.OidcProviderNative(this, "GitHubOidc", {
url: "https://token.actions.githubusercontent.com",
clientIds: ["sts.amazonaws.com"],
});
const role = new iam.Role(this, "DeployRole", {
roleName: "github-orders-deploy",
maxSessionDuration: Duration.hours(1),
assumedBy: new iam.OpenIdConnectPrincipal(provider, {
StringEquals: {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
"token.actions.githubusercontent.com:sub":
`repo:${props.repo}:environment:${props.environment}`,
},
}),
});
// CloudFormation does the real work through the bootstrap execution role,
// so CI only needs to assume the CDK bootstrap roles.
role.addToPolicy(new iam.PolicyStatement({
actions: ["sts:AssumeRole"],
resources: [`arn:aws:iam::${this.account}:role/cdk-hnb659fds-*`],
}));
new CfnOutput(this, "DeployRoleArn", { value: role.roleArn });
}
}
const app = new App();
new GitHubDeployAccessStack(app, "GitHubDeployAccess", {
env: { account: "111122223333", region: "us-east-1" },
repo: "acme/orders-service",
environment: "production",
});
app.synth();Cross-account deployment
Keeping production in a different account from dev (the multi-account strategy from the Architecture & Governance chapter) is normal, and there are two patterns. In the first, every target account has its own OIDC provider and role: the dev account's role trusts environment:dev and the prod account's role trusts environment:production. It is simple and keeps the blast radius small.
In the second, only a tooling (CI) account has the OIDC role, and target accounts are bootstrapped with cdk bootstrap --trust. --trust lets the tooling account assume the target account's bootstrap roles, while --cloudformation-execution-policies limits what CloudFormation may do there. The CI role's policy then lists target role ARNs such as arn:aws:iam::444455556666:role/cdk-hnb659fds-*.
# Run once in the PROD account (444455556666) with its admin credentials.
# Trust the tooling account and cap what CloudFormation may create there.
npx cdk bootstrap aws://444455556666/us-east-1 \
--trust 111122223333 \
--cloudformation-execution-policies \
arn:aws:iam::444455556666:policy/orders-cfn-execution
# Confirm the bootstrap version and the roles it created
aws ssm get-parameter --name /cdk-bootstrap/hnb659fds/version \
--query Parameter.Value --output text
aws iam list-roles --query "Roles[?starts_with(RoleName, 'cdk-hnb659fds')].RoleName"| OIDC role per account | Tooling account + --trust | |
|---|---|---|
| Setup | Simple, each account independent | Bootstrap trust to manage |
| Blast radius | One role = one account | The CI role reaches many accounts |
| Good fit | GitHub Actions with environments | CDK Pipelines, CodePipeline, many accounts |
The AWS-native alternative: CodePipeline and CodeBuild
If you want the whole CI/CD system inside AWS, use CodePipeline (the orchestrator that links stages) and CodeBuild (the service that runs build containers). GitHub is connected through CodeConnections (formerly CodeStar Connections). No OIDC is needed here: the CodeBuild project has a service role, and temporary credentials appear in the build container automatically. Approval gates use CodePipeline's Manual approval action, with SNS notifying the reviewers.
For CDK projects, the aws-cdk-lib/pipelines module (CDK Pipelines) builds CodePipeline as a self-mutating pipeline that updates itself, and adding a new stage takes a single line of code.
version: 0.2
phases:
install:
runtime-versions:
nodejs: 22
commands:
- npm ci
build:
commands:
- npm test
- npx cdk synth --quiet
artifacts:
base-directory: cdk.out
files:
- "**/*"| GitHub Actions + OIDC | CodePipeline + CodeBuild | |
|---|---|---|
| AWS credentials | OIDC token → role | CodeBuild service role (automatic) |
| Approval gate | Environment required reviewers | Manual approval action |
| Build environment | GitHub-hosted or self-hosted runners | CodeBuild containers, optionally in your VPC |
| Choose when | Code and PRs live in GitHub and developers know it | You need private network access, AWS-only audit, or CDK Pipelines |
In production
What a production pipeline looks like
A typical setup has three GitHub environments — dev, staging and production — each matching one AWS account. Each account has its own role whose trust policy allows only the matching environment. The production environment requires two reviewers and allows deployments only from main through a deployment branch rule. Every pull request runs cdk diff with a read-only role and posts the result as a PR comment.
During a migration, once the OIDC role is proven to work, deactivate the IAM user's access key, watch CloudTrail for about a week to confirm nothing still uses it, and then delete the user. More and more organizations also review their roles' trust policies with IAM Access Analyzer and block roles without a sub condition through SCPs or automated checks. In CloudTrail, AssumeRoleWithWebIdentity events trace back to the exact workflow run through the role session name.
Common mistakes
Common mistakes
- Leaving out the sub condition, or using a wildcard that is too broad. If only aud is checked, a workflow in any repository on GitHub can try to assume your role. StringLike with repo:acme/* lets every repo in the organization — including an intern's experiment — deploy to production.
- Mixing up environment and branch subjects. When the job has environment: production, sub becomes ...:environment:production rather than ...:ref:refs/heads/main. If the trust policy checks the branch form, you get 'Not authorized to perform sts:AssumeRoleWithWebIdentity'.
- Forgetting id-token: write. configure-aws-credentials then fails to get credentials. Also note that a job-level permissions block replaces the workflow-level one rather than adding to it.
- Giving the CI role AdministratorAccess. CDK only needs to assume the bootstrap roles; with admin, one compromised step in the workflow controls the whole account.
- Running fork code under the pull_request_target trigger and assuming an AWS role. That runs a stranger's code with your secrets and full permissions.
💰 Cost & Cleanup
IAM OIDC providers, IAM roles and STS calls are free. GitHub-hosted runner minutes are free for public repositories; private repositories are charged beyond the plan's monthly allowance (check GitHub's pricing). CodeBuild charges per build minute, and CodePipeline charges per active pipeline or per execution depending on the pipeline type. The stacks the pipeline deploys cost the same as in the previous lessons. Delete the role and provider when you finish the lab — they are free, but an unused trust relationship is a security risk.
Clean up when you are done
aws iam delete-role-policy --role-name github-orders-deploy \
--policy-name assume-cdk-bootstrap-roles
aws iam delete-role --role-name github-orders-deploy
# Only if no other role in this account still uses the GitHub provider:
aws iam delete-open-id-connect-provider --open-id-connect-provider-arn \
arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.comMini challenge
A read-only role for pull requests
Write the trust policy for a new role, github-orders-plan, that pull requests use to run cdk diff. It is separate from the deploy role and gets only read-only permissions such as ReadOnlyAccess. One catch: cdk diff reads the deployed template through the CDK bootstrap lookup role (cdk-hnb659fds-lookup-role-111122223333-*), so this role's permission policy also needs sts:AssumeRole on that lookup role. (This challenge asks only for the trust policy.)
- Use the GitHub OIDC provider in account 111122223333 as the Federated principal
- Check aud equals sts.amazonaws.com with StringEquals
- Allow sub only for pull_request events of the acme/orders-service repo, exactly
- No wildcards at all (no StringLike, no *)
Expected: A PR workflow can assume github-orders-plan and run cdk diff thanks to ReadOnlyAccess plus sts:AssumeRole on the lookup role, while cdk deploy fails with AccessDenied. A workflow triggered by a push to main is refused when it tries to assume this role, because its sub does not match.
Show hint
A pull_request event's sub has the form repo:OWNER/REPO:pull_request, with no branch name. Starting from the syntax section's trust policy, you only change the sub value.
Show solution
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "GitHubActionsPullRequestPlan",
"Effect": "Allow",
"Principal": {
"Federated":
"arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
"token.actions.githubusercontent.com:sub":
"repo:acme/orders-service:pull_request"
}
}
}
]
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Long-lived access keys in CI never expire and work from anywhere once leaked — switch to per-run temporary credentials with OIDC.
- Use an IAM OIDC provider plus a role with sts:AssumeRoleWithWebIdentity, and check aud and sub exactly with StringEquals.
- Grant id-token: write only to the deploy job and use configure-aws-credentials with role-to-assume.
- For CDK, let the CI role only assume the bootstrap roles; go cross-account with --trust or with one role per account.
- Put an approval gate in front of production: GitHub environment required reviewers or a CodePipeline manual approval.
IAM: Create an OpenID Connect (OIDC) identity provider — AWS Documentation
IAM: Create a role for OpenID Connect federation — AWS Documentation
AWS CodePipeline User Guide — AWS Documentation