Skip to Content
Cloud Engineering Academy
9. DevOps & CI/CD

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.

intermediate⏱ 1 h 40 min🟢 FreeDOP-C02DVA-C03SCS-C03

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.com once per account, with CDK (C#) or Terraform.
  • Write a trust policy whose aud and sub conditions pin a role to exactly one repository and one environment or branch, and recognise the unsafe patterns (missing sub, wildcards, the wrong operator).
  • Predict the sub claim for a push to main, 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: write and aws-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

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?

  1. AWS is told once, in advance, "I trust tokens signed by token.actions.githubusercontent.com". This registration is the IAM OIDC identity provider.
  2. A role says "anyone who presents a valid GitHub token whose claims match these conditions may assume me".
  3. 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

ConcernStored access keyOIDC federation
LifetimeUntil rotated, often yearsOne role session, one hour by default (configurable up to the role's maximum)
Where it livesCI secret store, laptops, logsNowhere; minted per job
ScopeWhatever the IAM user can do, from anywhereOne role, only for jobs whose claims match
AuditAccessKeyId in CloudTrail, but not which workflow run used itSession name and web identity subject appear in CloudTrail for every call
RevocationDelete or deactivate the key and update every copyEdit 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:TokenIssueTime to 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 main can still use a role pinned to main. OIDC removes stored credentials; it does not replace review, branch protection and scanning.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS / GitHub equivalentWhat's different
Azure DevOps service connection using a client secretIAM user access key in a CI secretBoth 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 policySame 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:prodTrust policy condition on token.actions.githubusercontent.com:subAzure matches the subject exactly. AWS lets you use StringLike with wildcards, which is where mistakes happen
App registration / service principal with role assignmentsIAM role with an identity policyAWS 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 workloadOIDC is the equivalent for workloads that run outside AWS
Conditional Access on the service principalConditions in the trust policy, SCPs, aws:SourceIp is not available for GitHub-hosted runnersRely 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:

RoleWho may assume itWhy
hl-m09-gh-ecr-pushPushes to main of one repositoryBuilding an image is the only thing that needs to write to the registry
hl-m09-gh-deploy-testJobs in environment testDeploy to the test account
hl-m09-gh-deploy-prodJobs in environment prodEnvironment 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:

ClaimExampleUse in a trust policy
isshttps://token.actions.githubusercontent.comFixed by the provider; you do not write it
audsts.amazonaws.comAlways require it with StringEquals; it stops tokens minted for another service being replayed
subrepo:harbourline-learn/accounts-api:environment:prodThe workhorse condition. Names repository plus context
repositoryharbourline-learn/accounts-apiAlso available in some configurations; check whether your trust policy can use it directly ⚠ VERIFY
refrefs/heads/mainBranch or tag of the run
environmentprodPresent when the job declares an environment
job_workflow_refOWNER/REPO/.github/workflows/release.yml@refs/heads/mainWhich workflow file ran; useful for reusable workflows
actor, run_idpriya.shah, 1234567890Audit 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 situationsub
Job declares environment: prodrepo:ORG/REPO:environment:prod
pull_request event, no environmentrepo:ORG/REPO:pull_request
Push or other event, branch, no environmentrepo:ORG/REPO:ref:refs/heads/main
Same, for a tagrepo: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:

  1. Console → IAM → Identity providers → Add provider.
  2. Provider type OpenID Connect. Provider URL https://token.actions.githubusercontent.com. Audience sts.amazonaws.com. Choose Add provider.
  3. 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:

  1. IAM → Roles → Create role → Web identity.
  2. Identity provider: token.actions.githubusercontent.com. Audience: sts.amazonaws.com.
  3. The wizard offers GitHub organisation, repository and branch fields and writes a sub condition from them. Check the generated JSON on the next screen: wizard output can use StringLike, and you should replace it with StringEquals and an exact value if you do not need a wildcard.
  4. Attach the permissions policy (create it first) and name the role hl-m09-gh-deploy-prod. Add tags Project=cea-lab, Lab=m09-delivery-pipeline, Environment=learn.

Read the evidence:

  1. Console → CloudTrail → Event history, filter Event name = AssumeRoleWithWebIdentity.
  2. Open an event and read requestParameters.roleSessionName, the web identity subject recorded under userIdentity (the field name varies, so look for the sub value) ⚠ VERIFY, and sourceIPAddress.

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 $P

Step 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.

GitHubOidcStack.cs
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:

.github/workflows/release.yml (deploy-test job, excerpt)
  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:

TrustPolicyTests.cs (shape of the lab 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 1

The 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

  1. 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.
  2. environment: test — changes the sub claim to the environment form, and makes GitHub apply the environment's protection rules before the job starts. For prod, the required-reviewers rule runs here.
  3. role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }} — a repository or environment variable. The ARN is not secret. Per-environment variables let test and prod use different roles with identical workflow code.
  4. role-session-name — becomes part of the session ARN and appears in every CloudTrail event the job causes. Including run_id lets an auditor jump from an AWS event to the exact workflow run.
  5. In the CDK class, WebIdentityPrincipal(providerArn, conditions) builds the trust statement with action sts:AssumeRoleWithWebIdentity. The dictionary maps operator to condition keys. The nested keys token.actions.githubusercontent.com:aud and :sub are not arbitrary: IAM derives them from the provider URL without the scheme.
  6. 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.
  7. In Terraform, for_each = local.role_subjects creates one role per key with one subject each. This pattern makes it impossible to share a role across contexts by accident.
  8. iam:PassRole with iam: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

PatternWhy it is dangerousFix
No sub condition at allAny repository on GitHub can assume the role, because the audience is the same for everyone. The lab's trust-bad-no-sub.json demonstrates thisAlways 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 roleOne role per repository and context, exact match
StringLike repo:*/accounts-api:*Any owner's repository named accounts-api: a fork or an attacker's copyNever put a wildcard before the owner
Matching only on audsts.amazonaws.com is the default audience for every GitHub tenantRequire sub too
Trusting ref:refs/heads/* for a prod roleAny branch, including one created by a contributor with write access, can deployUse the environment subject, with required reviewers and a branch rule
Condition operator StringEquals on a list that you build with StringLike semanticsWildcard characters are literal in StringEquals, so the role silently never matchesUse the operator that does what you intend, and test with the evaluator
Reusing one role for test and prodA mistake in test-only code can reach prodOne 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 declare environment: 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 AssumeRoleWithWebIdentity events for the prod role where the subject is not environment:prod. This should never fire, because STS would have denied it; but denied attempts are the interesting ones (errorCode present).
  • 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: write on 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 sub is 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

SymptomLikely causeFix
Not authorized to perform sts:AssumeRoleWithWebIdentitysub 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 loadedJob lacks permissions: id-token: writeAdd it to the job, not only the workflow
No OpenIDConnect provider found in your account for https://token.actions.githubusercontent.comProvider not created in this accountCreate it (CDK, Terraform or CLI)
Incorrect token audienceToken requested for a different audience than the provider's client IDLeave 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 removedMatch the trust policy to the final job definition
EntityAlreadyExists when creating the providerOne provider per URL per accountImport it into IaC or set create_oidc_provider = false
Role assumed, then AccessDenied on iam:PassRoleDeploy role cannot pass the task roleAdd iam:PassRole scoped to the two task roles with iam:PassedToService
Session expires mid-deployDeployment longer than the role's sessionShorten 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 $P

With 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, run trust-eval for the prod-deploy.json and fork-prod-environment.json claims against trust-deploy-prod.json. Then run trust-lint on trust-bad-no-sub.json and trust-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.yml at refs/heads/main may assume, whichever application repository calls it. Say which claim you need in sub, 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

Knowledge check

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; calls AssumeRoleWithWebIdentity; STS validates the signature against the registered provider and evaluates the role's trust policy against aud and sub; the job receives temporary credentials. Nothing long-lived is stored.
  • What would you check in a trust policy during a review? Exact sub match, aud present, no wildcards before the owner, operator is StringEquals, 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 to main and requires reviewers with self-review blocked; workflow files are protected by CODEOWNERS.
  • What changes for repositories created after GitHub's immutable-ID change? The sub includes 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

Completion checklist

  • I can explain the OIDC flow in two sentences without using the word "key"
  • I ran trust-eval on a hostile claims file and explained why it was denied
  • I can write the sub for a branch, a pull request and an environment job
  • I created or reviewed a role with exact aud and sub conditions
  • 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 aud and sub, with StringEquals and 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: write on the single job that needs it, pin third-party actions, and test the negative cases.

Further reading

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.

On this page