GitHub Actions with OIDC: deploy to AWS with no stored keys
Create an IAM OIDC identity provider for GitHub, write trust policies that pin a role to one repository and one environment or branch, and prove that forks, pull requests and sibling repositories cannot assume it.
Assumes: .NET 10 LTS · GitHub Actions (aws-actions/configure-aws-credentials v6.3.0) · Amazon.CDK.Lib 2.277.0 · Terraform AWS provider v6 · AWS CLI v2 · Region us-east-1. Verified against official sources on 2026-11-18.
Learning objectives
By the end of this lesson you can:
- Explain, step by step, what happens between a GitHub job starting and AWS handing it temporary credentials with
AssumeRoleWithWebIdentity. - Create the IAM OIDC identity provider for
token.actions.githubusercontent.comonce per account, with CDK (C#) or Terraform. - Write a trust policy whose
audandsubconditions pin a role to exactly one repository and one environment or branch, and recognise the unsafe patterns (missingsub, wildcards, the wrong operator). - Predict the
subclaim for a push tomain, a pull request, a job that declares an environment, and a repository that uses the newer immutable owner and repository IDs. - Configure a workflow with
permissions: id-token: writeandaws-actions/configure-aws-credentials, and debug a failed assume-role by printing the claims. - Show with the lab tool that a fork, a pull request and a sibling repository are all denied.
Prerequisites
- CI/CD concepts on AWS — stages, artefacts and environments.
- Git and GitHub for regulated teams — protected branches, rulesets and environments.
- Module 1: AWS fundamentals — IAM roles and STS.
- Tools: AWS CLI v2 with the
learn-sandboxprofile, a GitHub repository you own, Docker or the .NET 10 SDK for the lab tool.
Why this matters in banking
A deployment pipeline needs to change production. Until a few years ago the usual answer was an IAM user with an access key stored as a CI secret. That key is valid until someone rotates it, works from any network, and appears in every place the secret is copied: a build log, a developer laptop, an exported environment file. When Harbourline's internal-audit team asks "how do you know the production deploy credential has never been used from outside your pipeline?", a stored key has no good answer.
OpenID Connect (OIDC) federation changes the question. GitHub signs a short-lived identity token for each job that says "this job runs in repository X, on branch Y, in environment Z". AWS verifies the signature, checks the claims against the role's trust policy, and returns credentials that expire in about an hour. There is nothing to rotate and nothing to steal from the secret store, because nothing was stored. The security control moves into the trust policy, and that is also where the new mistakes live: a trust policy that says "any repository on GitHub" turns a secure design into an open door.
This lesson is the most security-relevant in the module. Read the trust-policy sections slowly.
The idea in plain language
Your workflow runs on a machine GitHub owns. That machine has never met AWS. How can AWS trust it?
- AWS is told once, in advance, "I trust tokens signed by
token.actions.githubusercontent.com". This registration is the IAM OIDC identity provider. - A role says "anyone who presents a valid GitHub token whose claims match these conditions may assume me".
- At run time the job asks GitHub for a token, hands it to AWS STS, and receives temporary credentials for that one role.
Analogy: a bank's visitor badge. Reception does not know you personally, but the bank has agreed to accept badges issued by a partner firm's security desk. The badge says who you are and which meeting you are attending. Reception (STS) checks the badge is genuine (signature), then checks the meeting list on the door (trust policy). A genuine badge for the wrong meeting opens nothing.
The conditions you write are the meeting list. Everything depends on getting them exact.
What problem the AWS service solves
| Concern | Stored access key | OIDC federation |
|---|---|---|
| Lifetime | Until rotated, often years | One role session, one hour by default (configurable up to the role's maximum) |
| Where it lives | CI secret store, laptops, logs | Nowhere; minted per job |
| Scope | Whatever the IAM user can do, from anywhere | One role, only for jobs whose claims match |
| Audit | AccessKeyId in CloudTrail, but not which workflow run used it | Session name and web identity subject appear in CloudTrail for every call |
| Revocation | Delete or deactivate the key and update every copy | Edit the trust policy; takes effect for new sessions immediately |
Honest limits:
- One provider per URL per account. An account can have a single IAM OIDC provider for
token.actions.githubusercontent.com. In a multi-account setup you create it in each account the pipeline deploys to, because trust is evaluated by the account that owns the role. - Existing sessions survive a trust change. If you tighten the trust policy, sessions already issued remain valid until they expire. For an incident you can attach an inline policy that denies on
aws:TokenIssueTimeto revoke older sessions. - GitHub is a dependency. If GitHub's token service is down, your pipeline cannot assume roles. Break-glass access (see the environment separation lesson) is the fallback.
- The token proves where the job ran, not that the code is good. A malicious change merged to
maincan still use a role pinned tomain. OIDC removes stored credentials; it does not replace review, branch protection and scanning.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS / GitHub equivalent | What's different |
|---|---|---|
| Azure DevOps service connection using a client secret | IAM user access key in a CI secret | Both are long-lived and both are the thing to eliminate |
| Workload identity federation for Azure Pipelines or GitHub (federated credential on an app registration) | IAM OIDC provider + role trust policy | Same idea. In Azure, the federated credential names issuer, subject and audience; in AWS the same three things live in the provider and the trust policy conditions |
Federated credential subject repo:org/repo:environment:prod | Trust policy condition on token.actions.githubusercontent.com:sub | Azure matches the subject exactly. AWS lets you use StringLike with wildcards, which is where mistakes happen |
| App registration / service principal with role assignments | IAM role with an identity policy | AWS splits "who can become this role" (trust policy) from "what the role can do" (permissions policy) |
| Managed identity (no secret at all) | Role assumed by an AWS service or workload | OIDC is the equivalent for workloads that run outside AWS |
| Conditional Access on the service principal | Conditions in the trust policy, SCPs, aws:SourceIp is not available for GitHub-hosted runners | Rely on claim conditions, not on network location |
Architecture
Security-boundary view
A pull request job from the same repository carries the subject ending in pull_request, which matches neither role. A fork carries a different repository name, so the sub match fails on the owner and repository part. Both are denied by absence of a matching condition, not by an explicit deny.
Step-by-step implementation
Create the identity provider (once per account)
The provider URL is https://token.actions.githubusercontent.com and the client ID (audience) is sts.amazonaws.com. You no longer need to supply a certificate thumbprint for GitHub: IAM validates the issuer's TLS certificate using its own library of trusted certificate authorities. If an older tutorial tells you to paste a thumbprint, it predates that change ⚠ VERIFY if your tooling still insists on one.
Decide which GitHub context deserves which role
Make a table before you write any JSON. For the module project:
| Role | Who may assume it | Why |
|---|---|---|
hl-m09-gh-ecr-push | Pushes to main of one repository | Building an image is the only thing that needs to write to the registry |
hl-m09-gh-deploy-test | Jobs in environment test | Deploy to the test account |
hl-m09-gh-deploy-prod | Jobs in environment prod | Environment prod has required reviewers, so assuming this role is gated by a human approval |
Using environments for deploy roles is deliberate: GitHub only issues a token with the environment:prod subject after the environment's protection rules (reviewers, branch restrictions) pass. The environment is the lock on the door; the trust policy checks the lock was used.
Write the trust policy with exact matches
Use StringEquals on both claims. Never leave out sub; never use a bare wildcard (more on this below).
Write a separate, narrow permissions policy
The trust policy answers "who", the permissions policy answers "what". The prod deploy role gets ECS update on one service and iam:PassRole for two named roles, not AdministratorAccess.
Configure the workflow
Give the job permissions: id-token: write, use aws-actions/configure-aws-credentials with role-to-assume, and keep the role ARN in a variable, not a secret. It is an identifier, and showing it in logs helps auditors.
Test the negative cases before you trust the role
Run the lab tool against hostile claim files (a fork, a pull request, another repository, a wrong audience) and confirm every one is denied. Then run one real workflow and read the CloudTrail event.
The claims you will actually use
GitHub's token contains many claims. For trust policies these matter:
| Claim | Example | Use in a trust policy |
|---|---|---|
iss | https://token.actions.githubusercontent.com | Fixed by the provider; you do not write it |
aud | sts.amazonaws.com | Always require it with StringEquals; it stops tokens minted for another service being replayed |
sub | repo:harbourline-learn/accounts-api:environment:prod | The workhorse condition. Names repository plus context |
repository | harbourline-learn/accounts-api | Also available in some configurations; check whether your trust policy can use it directly ⚠ VERIFY |
ref | refs/heads/main | Branch or tag of the run |
environment | prod | Present when the job declares an environment |
job_workflow_ref | OWNER/REPO/.github/workflows/release.yml@refs/heads/main | Which workflow file ran; useful for reusable workflows |
actor, run_id | priya.shah, 1234567890 | Audit information, not for trust decisions |
The default sub formats
By default GitHub builds sub like this (the table assumes the repository is ORG/REPO):
| Job situation | sub |
|---|---|
Job declares environment: prod | repo:ORG/REPO:environment:prod |
pull_request event, no environment | repo:ORG/REPO:pull_request |
| Push or other event, branch, no environment | repo:ORG/REPO:ref:refs/heads/main |
| Same, for a tag | repo:ORG/REPO:ref:refs/tags/v1.4.0 |
Note the order of precedence: when a job names an environment, the environment subject replaces the branch subject. So a job in the prod environment does not carry ref:refs/heads/main in sub. If you want to require both "environment prod" and "branch main", use the environment's deployment branch restriction in GitHub (so only main can deploy to prod), and check the ref claim separately if your trust policy supports it ⚠ VERIFY, or customise the sub template as described next.
Immutable subjects: owner and repository IDs
Repository names can be reused. If a repository is deleted or renamed and an attacker registers the old name, a trust policy that matched on the name alone might start trusting the wrong repository. GitHub's newer format puts the numeric, permanent owner and repository IDs into the subject, separated from the name with @, for example:
repo:harbourline-learn@81234567/accounts-api@912345678:environment:prod
According to GitHub's documentation, repositories created after 15 July 2026, and any repository that opts in, use this format, and renames or transfers after that date also switch the format. The IDs remain in the subject even when you customise the claims. It is not available on GitHub Enterprise Server. Because the format differs, a trust policy copied from an old blog post silently stops matching on a new repository. That is a safe failure (denied), but it is a common reason for "Not authorized to perform sts:AssumeRoleWithWebIdentity" on a new repository. Verify the exact format for your repository by printing the token (see Troubleshooting) ⚠ VERIFY against your GitHub plan and repository creation date.
The lab provides both versions: policies/trust-deploy-prod.json (classic) and policies/trust-deploy-prod-immutable.json (IDs). The Terraform variable github_subject_prefix switches the prefix.
Customising sub
Organisation administrators can change which claims make up sub through the GitHub REST API (include_claim_keys, for example repo, context, job_workflow_ref). Repositories reset to the default with use_default: true. Two cautions from GitHub's guidance: create or update the AWS trust conditions before applying a new template, or tokens will be rejected; and treat the template as part of your security configuration, protected by the same review as IAM.
Pinning a workflow file with job_workflow_ref is powerful for banks: it lets you say "only the reusable release workflow in the platform repository, at a protected ref, may assume the prod role", so application teams cannot assume it from their own workflows.
AWS Console instructions
Create the provider:
- Console → IAM → Identity providers → Add provider.
- Provider type OpenID Connect. Provider URL
https://token.actions.githubusercontent.com. Audiencests.amazonaws.com. Choose Add provider. - If the console reports the provider already exists, another stack or teammate created it. Reuse it: you cannot create a second one.
Create a role:
- IAM → Roles → Create role → Web identity.
- Identity provider:
token.actions.githubusercontent.com. Audience:sts.amazonaws.com. - The wizard offers GitHub organisation, repository and branch fields and writes a
subcondition from them. Check the generated JSON on the next screen: wizard output can useStringLike, and you should replace it withStringEqualsand an exact value if you do not need a wildcard. - Attach the permissions policy (create it first) and name the role
hl-m09-gh-deploy-prod. Add tagsProject=cea-lab,Lab=m09-delivery-pipeline,Environment=learn.
Read the evidence:
- Console → CloudTrail → Event history, filter Event name = AssumeRoleWithWebIdentity.
- Open an event and read
requestParameters.roleSessionName, the web identity subject recorded underuserIdentity(the field name varies, so look for thesubvalue) ⚠ VERIFY, andsourceIPAddress.
AWS CLI
P=learn-sandbox
# 1. Create the provider (only if it does not exist). No thumbprint is needed for GitHub.
aws iam create-open-id-connect-provider \
--url https://token.actions.githubusercontent.com \
--client-id-list sts.amazonaws.com \
--profile $P
# 2. Check whether it already exists, and which audiences it accepts.
aws iam list-open-id-connect-providers --profile $P
aws iam get-open-id-connect-provider \
--open-id-connect-provider-arn arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com \
--profile $P
# 3. Create the prod deploy role from the lab's trust policy (edit the account ID and repository first).
aws iam create-role --role-name hl-m09-gh-deploy-prod \
--assume-role-policy-document file://policies/trust-deploy-prod.json \
--max-session-duration 3600 \
--tags Key=Project,Value=cea-lab Key=Lab,Value=m09-delivery-pipeline Key=Environment,Value=learn \
--profile $P
# 4. Attach the narrow permissions policy as an inline policy.
aws iam put-role-policy --role-name hl-m09-gh-deploy-prod \
--policy-name deploy-accounts-api-prod \
--policy-document file://policies/permissions-deploy-ecs.json \
--profile $P
# 5. Simulate what the role may do BEFORE the first pipeline run.
aws iam simulate-principal-policy \
--policy-source-arn arn:aws:iam::111122223333:role/hl-m09-gh-deploy-prod \
--action-names ecs:UpdateService ecs:DeleteCluster iam:CreateUser \
--query 'EvaluationResults[].[EvalActionName,EvalDecision]' --output table --profile $P
# 6. After a pipeline run: who assumed the role, and as which session?
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleWithWebIdentity \
--max-results 5 \
--query 'Events[].[EventTime,Username]' --output table --profile $PStep 5 should show ecs:UpdateService allowed and the other two implicitly denied. If iam:CreateUser is allowed, stop: the role is far too broad.
Infrastructure as code
The lab's infra/terraform/oidc.tf creates the provider, one ecr-push role pinned to refs/heads/main, and one deploy role per environment pinned to environment:<name>. Read it next to this lesson.
using System.Collections.Generic;
using Amazon.CDK;
using Amazon.CDK.AWS.IAM;
using Constructs;
namespace Harbourline.Delivery.Infra;
public sealed class GitHubOidcStack : Stack
{
private const string Issuer = "token.actions.githubusercontent.com";
public GitHubOidcStack(Construct scope, string id, IStackProps props) : base(scope, id, props)
{
// Subject prefix: classic "repo:OWNER/REPO" or the immutable "repo:OWNER@ID/REPO@ID".
var owner = (string?)Node.TryGetContext("githubOwner") ?? "harbourline-learn";
var repo = (string?)Node.TryGetContext("githubRepo") ?? "accounts-api";
var subjectPrefix = (string?)Node.TryGetContext("githubSubjectPrefix") ?? $"repo:{owner}/{repo}";
// One provider per account. In CDK the L2 construct creates a custom resource that registers it.
// Newer CDK versions also offer a native CloudFormation-backed variant; check the API docs
// for your Amazon.CDK.Lib version before choosing ⚠ VERIFY.
var provider = new OpenIdConnectProvider(this, "GitHub", new OpenIdConnectProviderProps
{
Url = $"https://{Issuer}",
ClientIds = new[] { "sts.amazonaws.com" },
});
var prodRole = new Role(this, "DeployProd", new RoleProps
{
RoleName = "hl-m09-gh-deploy-prod",
Description = "Assumed by GitHub Actions jobs in environment prod. No access keys.",
MaxSessionDuration = Duration.Hours(1),
AssumedBy = new WebIdentityPrincipal(provider.OpenIdConnectProviderArn, new Dictionary<string, object>
{
["StringEquals"] = new Dictionary<string, object>
{
[$"{Issuer}:aud"] = "sts.amazonaws.com",
[$"{Issuer}:sub"] = $"{subjectPrefix}:environment:prod",
},
}),
});
// Narrow permissions: update one ECS service, pass two named roles to ECS.
prodRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps
{
Sid = "UpdateOneService",
Actions = new[] { "ecs:UpdateService", "ecs:DescribeServices" },
Resources = new[] { $"arn:aws:ecs:{Region}:{Account}:service/hl-m09-cluster/hl-m09-accounts-api" },
}));
prodRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps
{
Sid = "PassOnlyTheTaskRolesToEcs",
Actions = new[] { "iam:PassRole" },
Resources = new[]
{
$"arn:aws:iam::{Account}:role/hl-m09-accounts-api-task",
$"arn:aws:iam::{Account}:role/hl-m09-accounts-api-execution",
},
Conditions = new Dictionary<string, object>
{
["StringEquals"] = new Dictionary<string, object> { ["iam:PassedToService"] = "ecs-tasks.amazonaws.com" },
},
}));
// Inside a Stack, Amazon.CDK.Tags.Of(this) resolves to the stack's own property: qualify it.
Amazon.CDK.Tags.Of(this).Add("Project", "cea-lab");
Amazon.CDK.Tags.Of(this).Add("Lab", "m09-delivery-pipeline");
Amazon.CDK.Tags.Of(this).Add("Environment", "learn");
new CfnOutput(this, "DeployProdRoleArn", new CfnOutputProps { Value = prodRole.RoleArn });
}
}Both examples use exact StringEquals. Whatever IaC scanner your bank uses, add a rule that rejects any GitHub trust policy whose sub condition uses a wildcard before the repository name; the lab's trust-lint command does exactly that.
Complete code
The workflow side is short. This is the deploy job from the module project, with every line that matters to OIDC commented:
deploy-test:
name: Deploy to test
needs: build-push
runs-on: ubuntu-latest
environment: test # makes the token's sub: repo:OWNER/REPO:environment:test
permissions:
contents: read
id-token: write # allows requesting the OIDC token; grants nothing in AWS by itself
steps:
- uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0
with:
role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }}
role-session-name: gh-${{ github.run_id }}-test
aws-region: ${{ vars.AWS_REGION }}And a C# helper that makes the trust decision testable. The lab's Harbourline.Delivery library evaluates a trust policy against a claims file, using the same matching rules as IAM for StringEquals and StringLike. A condensed look at how you use it from a test:
using Harbourline.Delivery.Oidc;
using Xunit;
public class ProdRoleTrustTests
{
private const string Policy = "policies/trust-deploy-prod.json";
[Theory]
[InlineData("policies/claims/prod-deploy.json", true)] // job in environment prod
[InlineData("policies/claims/fork-prod-environment.json", false)] // same environment name, different repository
[InlineData("policies/claims/other-repo-prod.json", false)] // sibling repository
[InlineData("policies/claims/pull-request.json", false)] // pull_request subject
[InlineData("policies/claims/feature-branch.json", false)] // branch push
[InlineData("policies/claims/wrong-audience.json", false)] // token minted for another audience
public void Only_the_prod_environment_of_this_repository_is_allowed(string claimsFile, bool expected)
{
var claims = GitHubOidcClaims.FromJson(File.ReadAllText(claimsFile));
var result = TrustPolicyEvaluator.Evaluate(File.ReadAllText(Policy), claims);
Assert.Equal(expected, result.IsAllowed);
}
}Run it from the lab folder, with no AWS account:
dotnet run --project src/Harbourline.Delivery -- trust-eval policies/trust-deploy-prod.json policies/claims/prod-deploy.json # Allowed, exit 0
dotnet run --project src/Harbourline.Delivery -- trust-eval policies/trust-deploy-prod.json policies/claims/fork-prod-environment.json # ImplicitDeny, exit 1
dotnet run --project src/Harbourline.Delivery -- trust-lint policies/trust-bad-wildcard.json # Error HL003, exit 1The CI workflow runs trust-lint on every trust policy the roles use, so a pull request that widens a trust policy fails before anyone reads it. Treat the evaluator as a learning and regression aid: IAM is the authority, and simulate-principal-policy does not evaluate trust policies, so the real test is an actual workflow run ⚠ VERIFY.
Code explained line by line
permissions: id-token: write— without it the runner never receives the variables needed to request a token, and the credentials action fails with "Credentials could not be loaded". Set it on the job that needs it, not on the whole workflow, so build and test jobs never obtain a token.environment: test— changes thesubclaim to the environment form, and makes GitHub apply the environment's protection rules before the job starts. Forprod, the required-reviewers rule runs here.role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }}— a repository or environment variable. The ARN is not secret. Per-environment variables lettestandproduse different roles with identical workflow code.role-session-name— becomes part of the session ARN and appears in every CloudTrail event the job causes. Includingrun_idlets an auditor jump from an AWS event to the exact workflow run.- In the CDK class,
WebIdentityPrincipal(providerArn, conditions)builds the trust statement with actionsts:AssumeRoleWithWebIdentity. The dictionary maps operator to condition keys. The nested keystoken.actions.githubusercontent.com:audand:subare not arbitrary: IAM derives them from the provider URL without the scheme. MaxSessionDuration = Duration.Hours(1)— the role's maximum. A deploy that needs longer than the session should be shortened or restructured, not given a twelve-hour role.- In Terraform,
for_each = local.role_subjectscreates one role per key with one subject each. This pattern makes it impossible to share a role across contexts by accident. iam:PassRolewithiam:PassedToService— the deploy role may hand only two named roles to ECS. Without this restriction, a deploy role could pass a more powerful role to a task it controls, which is a privilege-escalation path.
Security considerations
The unsafe patterns
| Pattern | Why it is dangerous | Fix |
|---|---|---|
No sub condition at all | Any repository on GitHub can assume the role, because the audience is the same for everyone. The lab's trust-bad-no-sub.json demonstrates this | Always require sub with an exact value |
StringLike repo:harbourline-learn/* | Every repository in the organisation, including a throw-away test repo with weak protections, can assume the production role | One role per repository and context, exact match |
StringLike repo:*/accounts-api:* | Any owner's repository named accounts-api: a fork or an attacker's copy | Never put a wildcard before the owner |
Matching only on aud | sts.amazonaws.com is the default audience for every GitHub tenant | Require sub too |
Trusting ref:refs/heads/* for a prod role | Any branch, including one created by a contributor with write access, can deploy | Use the environment subject, with required reviewers and a branch rule |
Condition operator StringEquals on a list that you build with StringLike semantics | Wildcard characters are literal in StringEquals, so the role silently never matches | Use the operator that does what you intend, and test with the evaluator |
| Reusing one role for test and prod | A mistake in test-only code can reach prod | One role per environment, in separate accounts |
⚠ Learning shortcut — not for production
The lab creates the OIDC provider and all three roles in a single sandbox account, so that you can complete the exercises with one login. In production each environment lives in its own AWS account with its own provider and role, created by a platform pipeline that application teams cannot edit (see Environment separation). The roles should also be protected by a service control policy that stops anyone changing the provider or trust policies except a named platform role.
Environments and approval
A trust policy that names environment:prod is only as strong as the GitHub environment behind it. Check these in GitHub → Settings → Environments → prod:
- Required reviewers set, with Prevent self-review enabled so the person who triggered the run cannot approve it.
- Deployment branches and tags limited to
main(or protected release branches), so a feature branch cannot declareenvironment: prod. - Administrators are not allowed to bypass, if your plan offers that option ⚠ VERIFY.
If an attacker can edit a workflow file on a branch that is allowed to deploy to the environment, they can add their own steps after the approval. Protect .github/workflows/ with CODEOWNERS and branch rulesets, as the Git lesson describes.
Pull requests from forks
By default GitHub does not give workflows triggered by a fork's pull request any secrets, and the GITHUB_TOKEN is read-only. The OIDC token request is also unavailable to those runs in the default configuration ⚠ VERIFY for your event types. The dangerous triggers are pull_request_target and workflow_run, which run in the context of the base repository. Do not combine those with id-token: write and checkout of the pull request's code.
Pin third-party actions
aws-actions/configure-aws-credentials runs with the power to receive your credentials. The lab pins it to a full commit SHA with the tag as a comment, and uses Dependabot to propose reviewed updates. The pipeline security lesson goes deeper.
Detecting misuse
- Create an Amazon EventBridge rule or a CloudWatch Logs metric filter on CloudTrail
AssumeRoleWithWebIdentityevents for the prod role where the subject is notenvironment:prod. This should never fire, because STS would have denied it; but denied attempts are the interesting ones (errorCodepresent). - Add an alarm when the OIDC provider or any
hl-m09-gh-*trust policy changes (UpdateAssumeRolePolicy,DeleteOpenIDConnectProvider).
Banking use case
Harbourline's platform team owns the prod account. They provide a reusable release workflow in a central repository. Application teams call it with uses:. The prod deploy role's trust policy requires the job_workflow_ref of that central workflow at its protected branch and the application's environment name. A developer cannot copy the role ARN into a workflow of their own and assume it, because their workflow's job_workflow_ref differs. Internal audit samples ten production releases per quarter and asks for the evidence of who approved and which workflow ran: the CloudTrail event for the assume-role call carries the session name gh-<run_id>-prod, and the run page shows the approval. The release management lesson shows how to package it.
All names and data are fictional.
Common mistakes
- Forgetting
id-token: writeon the job → "Credentials could not be loaded" → add it to the job that calls the credentials action. - Copying a trust policy for a branch and using it for a job with an environment → the
subis now the environment form, so the role denies the job → match the subject the job actually produces. - Using the repository name when the repository now sends immutable IDs → denied after a rename or on a new repository → print the real token claims and use the right prefix.
- Putting the role ARN in a secret → it is masked in logs and hard to audit, and it does not need protecting → use a variable.
- Creating the provider in every stack → the second creation fails because one provider per URL is allowed → create it once per account in a foundation stack, or look it up.
- Wide permissions "to get it working" → the role is later reused for something else → start with the minimum, read the AccessDenied message, add one action at a time, and keep the diff in review.
- Assuming OIDC proves the code is safe → it proves where the job ran → pair it with branch protection, reviews and scanning.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Not authorized to perform sts:AssumeRoleWithWebIdentity | sub in the token does not match the trust policy (wrong environment, branch, repository name, or immutable ID format) | Print the token claims (below), compare with the trust policy, run trust-eval |
Credentials could not be loaded | Job lacks permissions: id-token: write | Add it to the job, not only the workflow |
No OpenIDConnect provider found in your account for https://token.actions.githubusercontent.com | Provider not created in this account | Create it (CDK, Terraform or CLI) |
Incorrect token audience | Token requested for a different audience than the provider's client ID | Leave the audience input of the action at its default sts.amazonaws.com |
Works from main, fails from the environment job (or the reverse) | Job's sub changed because environment: was added or removed | Match the trust policy to the final job definition |
EntityAlreadyExists when creating the provider | One provider per URL per account | Import it into IaC or set create_oidc_provider = false |
Role assumed, then AccessDenied on iam:PassRole | Deploy role cannot pass the task role | Add iam:PassRole scoped to the two task roles with iam:PassedToService |
| Session expires mid-deploy | Deployment longer than the role's session | Shorten the deployment or split the job; avoid raising the session to twelve hours |
To see what your job's token contains, add a temporary debugging step. Never print the token itself: it is a credential for its lifetime.
# Decode the payload of the OIDC token WITHOUT printing the raw token.
# ACTIONS_ID_TOKEN_REQUEST_URL and ACTIONS_ID_TOKEN_REQUEST_TOKEN exist only when id-token: write is set.
TOKEN=$(curl -sS -H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
"$ACTIONS_ID_TOKEN_REQUEST_URL&audience=sts.amazonaws.com" | jq -r .value)
echo "$TOKEN" | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/null | jq '{iss,aud,sub,repository,repository_owner,ref,environment,job_workflow_ref,actor}'Remove the step after use and rotate nothing: the token has already expired.
Cost and cleanup
Cost: free. The IAM OIDC provider, roles and STS calls are free. GitHub Actions minutes for a short workflow are small; public repositories are free, private repositories have a monthly allowance ⚠ VERIFY current allowance. The only thing this lesson can bill is whatever your test role deploys, and the lesson does not deploy resources.
Teardown:
P=learn-sandbox
# Remove role policies first, then the roles.
for R in hl-m09-gh-deploy-prod hl-m09-gh-deploy-test hl-m09-gh-ecr-push; do
for POL in $(aws iam list-role-policies --role-name $R --query 'PolicyNames[]' --output text --profile $P); do
aws iam delete-role-policy --role-name $R --policy-name $POL --profile $P
done
aws iam delete-role --role-name $R --profile $P
done
# Delete the provider only if no other roles or labs depend on it.
aws iam delete-open-id-connect-provider \
--open-id-connect-provider-arn arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com --profile $P
# Confirm nothing is left.
aws iam list-roles --query "Roles[?starts_with(RoleName, 'hl-m09-gh-')].RoleName" --profile $PWith Terraform, terraform destroy in infra/terraform removes all of it. Also delete the GitHub environment variables that hold role ARNs, so a later run fails immediately instead of half way.
Exercises
- 🟢 Guided: In
labs/m09-delivery-pipeline, runtrust-evalfor theprod-deploy.jsonandfork-prod-environment.jsonclaims againsttrust-deploy-prod.json. Then runtrust-lintontrust-bad-no-sub.jsonandtrust-bad-wildcard.json. Write one sentence per file explaining the decision. Walk through the same steps with real AWS in Lab 9.2. - 🟡 Challenge: Write a trust policy for a role that only the central reusable workflow
harbourline-platform/pipelines/.github/workflows/release.ymlatrefs/heads/mainmay assume, whichever application repository calls it. Say which claim you need insub, how you would create it, and what must happen in AWS before you apply the change. - 🔴 Live problem: A ticket reads: "Since we recreated the repository last week, deploys fail with
Not authorized to perform sts:AssumeRoleWithWebIdentity. Nothing changed in AWS. Fix it, and make sure it cannot happen silently again." Find the cause, fix it, and design a safeguard.
Assignment
Add a short docs/oidc.md to your portfolio repository containing: a diagram of your pipeline's role-per-context design; the three trust policies; the trust-eval output for each hostile claims file; and a one-paragraph answer to "how do we know a fork cannot deploy to production?". Keep it factual and mark anything you could not prove.
Solutions
prod-deploy.json has sub = repo:harbourline-learn/accounts-api:environment:prod and audience sts.amazonaws.com, so both conditions match: Allowed. fork-prod-environment.json has the right environment name but a different owner in the repository part of the subject, so StringEquals on sub fails: ImplicitDeny. There is no explicit Deny statement; the policy simply has no Allow that matches. That is why exact conditions are enough: absence of a match is a denial.
trust-bad-no-sub.json only checks the audience, so any GitHub repository passes: lint error. trust-bad-wildcard.json uses StringLike with a leading or organisation-wide wildcard, which trusts repositories you did not mean to: error HL003. The lesson is that a trust policy is reviewed like code and tested with hostile input, not only with the happy path.
Customise the sub template for the organisation (or the calling repositories) so that it includes job_workflow_ref, using the GitHub REST API's include_claim_keys. The subject then contains something like job_workflow_ref:harbourline-platform/pipelines/.github/workflows/release.yml@refs/heads/main, and the trust policy uses StringEquals on token.actions.githubusercontent.com:sub with that exact value. Before applying the template you must create or update the AWS trust conditions to the new subject (GitHub's guidance: conditions first, or tokens are rejected), and keep the old form temporarily if both must work during migration. Confirm the exact subject by printing a real token ⚠ VERIFY. The immutable owner and repository IDs stay in the subject regardless. Protect the central repository's branch so only reviewed code reaches refs/heads/main; otherwise the pinned reference is only as trustworthy as that branch.
Likely cause: the new repository was created after GitHub's immutable-subject date (15 July 2026) or opted in, so tokens now carry repo:OWNER@ID/REPO@ID:..., while the trust policy still holds repo:OWNER/REPO:.... Another candidate is that the repository was renamed or transferred, so the name part changed. Confirm by decoding a token with the debugging step and comparing to the trust policy. Fix: update the trust policy (Terraform variable github_subject_prefix in the lab) and apply through the normal reviewed pipeline.
Safeguard: a canary workflow that runs weekly and on trust-policy changes, assumes each role from the matching context, and calls sts get-caller-identity, alerting on failure; plus an EventBridge rule on UpdateAssumeRolePolicy. Add a lint check (trust-lint) that fails if a trust policy has no sub condition. The canary turns a silent drift into a visible failure before a release depends on it.
Knowledge check
Answer: aud (must equal sts.amazonaws.com) and sub (names the repository and context). Conditioning only on aud lets any GitHub repository assume the role, because every tenant can request that audience.
Answer: The environment form, repo:OWNER/REPO:environment:prod (or the immutable ID variant). It does not carry the branch form, because the environment takes precedence. A policy written for ref:refs/heads/main denies it.
Answer: StringLike accepts wildcards, so a pattern such as repo:ORG/* trusts every repository in the organisation. StringEquals forces an exact subject and makes mistakes fail closed.
Answer: On the job that assumes the role. That way only that job can request a token; build and test jobs, which run less trusted steps, cannot.
Answer: The fork's token has a different repository in sub, so the trust policy's exact match fails; additionally GitHub withholds secrets and restricts the token for fork pull requests by default. Denial comes from the absence of a matching Allow.
Answer: No. Existing sessions last until they expire. To cut them off early, add a deny based on the token issue time, and keep session durations short.
Interview questions
- Walk me through how a GitHub job gets AWS credentials without a stored key. The job requests a signed JWT from GitHub with audience
sts.amazonaws.com; callsAssumeRoleWithWebIdentity; STS validates the signature against the registered provider and evaluates the role's trust policy againstaudandsub; the job receives temporary credentials. Nothing long-lived is stored. - What would you check in a trust policy during a review? Exact
submatch,audpresent, no wildcards before the owner, operator isStringEquals, one role per context, permissions policy narrow, session duration short. - How do you stop a developer deploying to prod from a feature branch? Role trusts only
environment:prod; the GitHub environment limits deployment branches tomainand requires reviewers with self-review blocked; workflow files are protected by CODEOWNERS. - What changes for repositories created after GitHub's immutable-ID change? The
subincludes numeric owner and repository IDs, so old name-based trust policies stop matching. You update the policy and prefer the ID form because names can be reused. - Compare this with Azure workload identity federation. Same pattern: issuer, subject and audience are matched. In AWS the match lives in the role's trust policy and wildcards are possible, so exactness matters more.
Certification practice
A company deploys with GitHub Actions. A security review finds an IAM user access key stored as a repository secret. The team wants no long-term credentials, and only the main branch of one repository may deploy to the production account. Which solution meets this with the least operational overhead?
A. Rotate the access key every 30 days with a scheduled workflow.
B. Create an IAM OIDC identity provider for GitHub and a role whose trust policy has StringEquals conditions on aud and on sub for that repository and branch.
C. Store the key in AWS Secrets Manager and read it with the same key.
D. Create a role trusting the OIDC provider with only an aud condition, because the audience identifies the company.
Answer: B. It removes the stored credential and pins the role to one repository and ref. A keeps a long-lived key and adds rotation work. C needs a credential to fetch the credential: circular. D trusts every GitHub tenant, since the audience is the same for everyone.
A workflow fails at the credentials step with "Credentials could not be loaded". The role and provider exist and the trust policy is correct. What is the most likely cause?
A. The IAM role's maximum session duration is too long.
B. The job does not have permissions: id-token: write.
C. The provider needs a thumbprint.
D. The ECS service has no task role.
Answer: B. Without that permission the runner cannot request an OIDC token. A would give a different error at assume time. C is not required for GitHub, and the error would be at STS, not at loading. D is unrelated to the pipeline's credentials.
The prod deploy role trusts sub equal to repo:acme/app:ref:refs/heads/main. After adding environment: prod to the deploy job (for required reviewers), deployments fail with an authorisation error from STS. What should the engineer do?
A. Change aud to the environment name.
B. Update the trust policy's sub to repo:acme/app:environment:prod, since an environment replaces the branch form in the subject.
C. Remove id-token: write.
D. Add the ref to the role session name.
Answer: B. The subject format changes when a job declares an environment. A breaks the audience check. C would stop token requests entirely. D has no effect on trust evaluation.
Completion checklist
- I can explain the OIDC flow in two sentences without using the word "key"
- I ran
trust-evalon a hostile claims file and explained why it was denied - I can write the
subfor a branch, a pull request and an environment job - I created or reviewed a role with exact
audandsubconditions - I ran the cleanup steps and confirmed no
hl-m09-gh-roles remain
Key takeaways
- OIDC replaces stored AWS keys with short-lived credentials minted per job; the trust policy becomes the control.
- Always condition on both
audandsub, withStringEqualsand exact values, one role per context. - A job with an environment gets the environment subject, so environments with required reviewers gate production roles.
- Newer repositories can send immutable owner and repository IDs in
sub; verify the real format by decoding a token. - Put
id-token: writeon the single job that needs it, pin third-party actions, and test the negative cases.
Further reading
- OpenID Connect reference (GitHub Docs) — claim list, subject formats and customisation
- Create an OpenID Connect identity provider in IAM (AWS)
- Deployments and environments (GitHub Docs)
- Lab 9.2: OIDC deploy role
- Next: AWS CodeBuild, CodePipeline and CodeDeploy
Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.
CI/CD concepts on AWS: stages, artefacts, environments and where each tool fits
Learn the vocabulary and the shape of a delivery pipeline (build once, promote the same artefact, gate each stage), map every stage to GitHub Actions or the AWS developer tools, and choose between them with a decision rule you can defend to an architecture board.
AWS CodeBuild, CodePipeline and CodeDeploy
Build a .NET 10 image in CodeBuild with a buildspec, orchestrate it with a CodePipeline V2 pipeline that has a manual approval, understand where CodeDeploy fits, and decide when AWS-native tooling beats GitHub Actions.