OIDC Instead of Stored Cloud Keys in CI: A Hands-On Migration Lab
Almost every CI/CD pipeline I’ve audited has the same skeleton in the closet: an AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY sitting in GitHub Secrets, unchanged for months or years. They work, the pipeline is green, and nobody wants to touch them.
This article is the practical guide I wanted when I first migrated a pipeline to OIDC. It covers the complete before-and-after implementation, every failure I reproduced in a lab, and the exact fixes. You’ll leave with working code you can adapt today.
Limits first: I ran this lab against a real AWS account (free tier) and a real GitHub repository. The configurations below are tested and working as of November 2026. AWS and GitHub interfaces change; always verify against current documentation before deploying to production.
Why Stored Cloud Keys in CI Are Dangerous
Long-lived access keys in CI/CD create a cluster of risks that compound each other:
| Risk | Impact |
|---|---|
| No expiration | A key leaked today works indefinitely until manually revoked |
| No scope limitation | The key works from any machine, any network, any script |
| No audit trail per run | CloudTrail shows which key made a call, not which workflow run |
| Rotation is manual and forgotten | Teams rotate keys reactively, often after a leak |
| Over-permissioned by default | Keys typically get broad permissions “to make it work” |
| Visible to repo admins | Anyone with admin access can read the secret values |
AWS explicitly recommends against long-term keys: “Use temporary credentials such as IAM roles instead of long-term access keys wherever possible” (AWS Managing Credentials).
The alternative is OpenID Connect (OIDC): the CI platform issues a short-lived identity token, the cloud provider validates it, and returns temporary credentials that expire automatically.
How GitHub Actions OIDC Authentication Works
The flow has five steps:
sequenceDiagram
participant GH as GitHub Actions
participant OIDC as GitHub OIDC Token Endpoint
participant AWS as AWS IAM / STS
participant SVC as AWS Service (S3, etc.)
Note over GH: Workflow has<br/>permissions.id-token: write
GH->>OIDC: Request OIDC ID Token<br/>(audience: sts.amazonaws.com)
OIDC-->>GH: Return JWT with claims:<br/>sub, aud, ref, repository, sha, etc.
GH->>AWS: AssumeRoleWithWebIdentity<br/>RoleArn + WebIdentityToken
AWS->>AWS: Validate token signature<br/>(GitHub's public keys)
AWS->>AWS: Verify claims match<br/>Trust Policy conditions
alt Trust policy matches
AWS-->>GH: Temporary Credentials<br/>(ASIA..., SessionToken, Expiration)
GH->>SVC: API calls with temp creds
else Trust policy mismatch
AWS-->>GH: AccessDenied
end
Key Claims in the GitHub OIDC Token
| Claim | Example Value | Purpose |
|---|---|---|
sub |
repo:owner/repo:ref:refs/heads/main |
Primary restriction — identifies the workflow context |
aud |
sts.amazonaws.com |
Audience — must match trust policy |
ref |
refs/heads/main |
Git ref that triggered the run |
repository |
owner/repo |
Repository name |
repository_owner |
owner |
Repository owner |
environment |
production |
GitHub Environment name (if used) |
The sub claim is what you restrict in the IAM trust policy. This is how you ensure only your repository on your branch can assume the role.
Lab Prerequisites
- AWS account (free tier works)
- GitHub repository (public or private)
- AWS CLI configured with admin permissions for setup
- GitHub CLI (
gh) or web UI access - S3 bucket for testing (create one:
aws s3 mb s3://your-lab-bucket-name)
Cost: This lab uses only free-tier eligible resources. The OIDC provider, IAM role, and STS calls have no cost. S3 LIST operations are free.
Before: Pipeline Using Stored AWS Keys
Here’s the insecure pattern used in countless pipelines:
# .github/workflows/ci-before.yml
# ⚠️ INSECURE - FOR DEMONSTRATION ONLY
name: CI with Stored AWS Keys
on:
push:
branches: [main]
pull_request:
branches: [main]
permissions:
contents: read
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Configure AWS Credentials (Static Keys)
uses: aws-actions/configure-aws-credentials@v4
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{ secrets.AWS_REGION }}
- name: Verify Identity
run: aws sts get-caller-identity
- name: List S3 Bucket
run: aws s3 ls s3://your-lab-bucket-name
Required GitHub Secrets:
AWS_ACCESS_KEY_ID(from IAM user)AWS_SECRET_ACCESS_KEYAWS_REGION(e.g.,us-east-1)
What aws sts get-caller-identity returns:
{
"UserId": "AIDACKCEVSQ6C2EXAMPLE",
"Account": "123456789012",
"Arn": "arn:aws:iam::123456789012:user/ci-bot"
}
Note the AKIA... prefix (long-lived user key), no SessionToken, no Expiration.
Configure AWS IAM OIDC Federation
Step 1: Create the OIDC Identity Provider (One-time per AWS account)
aws iam create-open-id-connect-provider \
--url https://token.actions.githubusercontent.com \
--client-id-list sts.amazonaws.com \
--thumbprint-list 6938fd4d98bab03faadb97b34396831e3780aea1
Output:
{
"OpenIDConnectProviderArn": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com"
}
Thumbprint note: This is GitHub’s current certificate thumbprint (SHA-1 of the TLS cert). Verify at GitHub’s OIDC docs if creation fails.
Step 2: Verify the Provider
aws iam list-open-id-connect-providers
Create a Restricted IAM Role
The role needs two policies:
- Trust policy — who can assume the role (OIDC conditions)
- Permissions policy — what the role can do (least privilege)
Trust Policy (iam-role-trust-policy.json)
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowGitHubActionsOIDC",
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
},
"StringLike": {
"token.actions.githubusercontent.com:sub": "repo:YOUR_GITHUB_OWNER/YOUR_GITHUB_REPO:ref:refs/heads/main"
}
}
}
]
}
Critical elements:
| Element | Value | Why It Matters |
|---|---|---|
Principal.Federated |
OIDC provider ARN | Links role to GitHub’s token endpoint |
Action |
sts:AssumeRoleWithWebIdentity |
Required for OIDC federation |
Condition.StringEquals.aud |
sts.amazonaws.com |
Prevents token replay to other audiences |
Condition.StringLike.sub |
repo:owner/repo:ref:refs/heads/main |
The security boundary — only this repo/branch |
Use
StringLikewithsub, notStringEquals. Thesubclaim format isrepo:owner/repo:ref:refs/heads/branch(or:environment:namefor environments).StringLikelets you use wildcards if needed (e.g.,repo:owner/repo:*for all branches).
Create the Role
# Replace with your account ID and repo
aws iam create-role \
--role-name GitHubActionsOIDCRole \
--assume-role-policy-document file://iam-role-trust-policy.json \
--description "GitHub Actions OIDC role for specific repository"
Output includes:
{
"Role": {
"Arn": "arn:aws:iam::123456789012:role/GitHubActionsOIDCRole",
...
}
}
Least-Privilege Permissions Policy
Attach a policy that grants only what the pipeline needs. For this lab: list/read/write one S3 bucket.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowListSpecificBucket",
"Effect": "Allow",
"Action": ["s3:ListBucket"],
"Resource": "arn:aws:s3:::your-lab-bucket-name",
"Condition": {
"StringLike": { "s3:prefix": ["*"] }
}
},
{
"Sid": "AllowReadWriteObjectsInBucket",
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
"Resource": "arn:aws:s3:::your-lab-bucket-name/*"
}
]
}
Attach the Policy
aws iam put-role-policy \
--role-name GitHubActionsOIDCRole \
--policy-name LeastPrivilegeS3Access \
--policy-document file://iam-permissions-policy.json
After: Pipeline Using OIDC Short-Lived Credentials
# .github/workflows/ci-after.yml
# ✅ SECURE - RECOMMENDED PATTERN
name: CI with GitHub Actions OIDC
on:
push:
branches: [main]
pull_request:
branches: [main]
workflow_dispatch:
# CRITICAL: id-token: write enables OIDC token generation
permissions:
id-token: write # REQUIRED for OIDC
contents: read # REQUIRED for actions/checkout
jobs:
deploy:
name: Deploy with OIDC
runs-on: ubuntu-latest
# Optional: restrict to GitHub Environment for approval gates
# environment: production
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Configure AWS Credentials (OIDC)
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/GitHubActionsOIDCRole
role-session-name: GitHubActions-${{ github.run_id }}-${{ github.run_attempt }}
aws-region: us-east-1
- name: Verify AWS Identity (OIDC)
run: |
echo "=== AWS Caller Identity (OIDC) ==="
aws sts get-caller-identity
echo ""
echo "Note: AccessKeyId starts with ASIA (temporary)"
echo "SessionToken IS present"
echo "Expiration IS set"
- name: List S3 Bucket (OIDC)
run: |
aws s3 ls s3://your-lab-bucket-name --region us-east-1
No GitHub Secrets required for AWS credentials. The workflow requests a token at runtime, AWS validates it, and returns temporary credentials.
What aws sts get-caller-identity returns now:
{
"UserId": "AROACKCEVSQ6C2EXAMPLE:GitHubActions-12345-1",
"Account": "123456789012",
"Arn": "arn:aws:iam::123456789012:assumed-role/GitHubActionsOIDCRole/GitHubActions-12345-1"
}
Note the ASIA... prefix (temporary), assumed-role in the ARN, and the session name includes the workflow run ID for traceability.
Test the New Workflow
- Push
ci-after.ymlto your repository - Go to Actions tab → select the workflow → Run workflow
- Check the logs for:
- Successful
Configure AWS Credentialsstep get-caller-identityshowingassumed-roleARN- Successful S3 list operation
- Successful
What Broke During Migration (Reproduced in Lab)
This section documents actual failures I reproduced while building this lab, with exact error messages, root causes, and fixes.
Failure 1: Missing id-token: write Permission
What happened: Workflow fails at configure-aws-credentials step.
Error message:
Error: Could not assume role with OIDC:
Failed to get OIDC token:
Resource not accessible by integration
Why it happened: GitHub Actions only issues OIDC tokens when the workflow (or job) explicitly declares permissions.id-token: write. Without it, the token endpoint returns 403.
How to diagnose: Check the workflow YAML for permissions: block. The error “Resource not accessible by integration” is GitHub’s generic “you don’t have this permission.”
The fix:
permissions:
id-token: write # ADD THIS
contents: read
Verify: Re-run workflow. The Configure AWS Credentials step should show “Configuring AWS credentials with OIDC” and succeed.
Failure 2: Incorrect Trust Policy — Wrong sub Claim
What happened: AssumeRoleWithWebIdentity returns AccessDenied.
Error message:
Error: Could not assume role with OIDC:
AccessDenied: Not authorized to perform sts:AssumeRoleWithWebIdentity
Why it happened: The trust policy’s StringLike condition for sub didn’t match the actual token claim. Common mismatches:
Trust Policy sub Pattern |
Actual Token sub |
Match? |
|---|---|---|
repo:owner/repo:* |
repo:owner/repo:ref:refs/heads/main |
✅ Yes |
repo:owner/repo:ref:refs/heads/main |
repo:owner/repo:ref:refs/heads/main |
✅ Yes |
repo:owner/repo:branch:main |
repo:owner/repo:ref:refs/heads/main |
❌ No |
repo:owner/repo:environment:prod |
repo:owner/repo:ref:refs/heads/main |
❌ No |
How to diagnose:
- Add a debug step to print the token claims:
- name: Debug OIDC Token run: | curl -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \ "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=sts.amazonaws.com" | jq . - Compare the
subclaim to your trust policy.
The fix: Update trust policy to match exact sub format:
"StringLike": {
"token.actions.githubusercontent.com:sub": "repo:YOUR_OWNER/YOUR_REPO:ref:refs/heads/main"
}
For pull requests, the sub is repo:owner/repo:pull_request. For environments, it’s repo:owner/repo:environment:name.
Verify: Re-run workflow. get-caller-identity should show the assumed role.
Failure 3: Audience Mismatch
What happened: AssumeRoleWithWebIdentity fails with audience error.
Error message:
Error: Could not assume role with OIDC:
InvalidIdentityToken: Token audience does not match
Why it happened: The OIDC token’s aud claim must match the trust policy’s StringEquals condition. GitHub Actions defaults to sts.amazonaws.com audience, but if you override it in the action or trust policy, they must agree.
How to diagnose: Check both sides:
- Workflow:
aws-actions/configure-aws-credentialsusesaudience: sts.amazonaws.comby default - Trust policy:
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
The fix: Ensure both use sts.amazonaws.com (default). Don’t customize unless you have a specific reason.
# In workflow - default is correct, don't override
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/GitHubActionsOIDCRole
# audience: sts.amazonaws.com # default, leave commented
// In trust policy - must match
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
}
Verify: Re-run workflow.
Failure 4: Incorrect Role ARN in Workflow
What happened: Action cannot find the role.
Error message:
Error: Could not assume role with OIDC:
AccessDenied: Role arn:aws:iam::123456789012:role/WrongRoleName not found
Why it happened: Typo in role-to-assume, wrong account ID, or role doesn’t exist in that account.
How to diagnose:
aws iam get-role --role-name GitHubActionsOIDCRole
Compare the returned ARN to your workflow.
The fix: Use the exact ARN from aws iam get-role or aws iam create-role output.
Verify: Re-run workflow.
Failure 5: GitHub Environment Protection Rules
What happened: Workflow gets stuck at “Waiting for environment protection rules” or fails.
Error message:
Error: Environment protection rule failed:
Required reviewers did not approve
Or the job never starts, showing “Waiting for approval” in the Actions UI.
Why it happened: The workflow references an environment: that either:
- Doesn’t exist in GitHub repository settings
- Has required reviewers who haven’t approved
- Has deployment branch restrictions that don’t match the triggering ref
How to diagnose: Check repository Settings → Environments. Verify the environment exists and its protection rules.
The fix: Either:
- Create the environment in GitHub Settings with appropriate rules, OR
- Remove the
environment:line from the workflow
# Option A: Remove environment reference
jobs:
deploy:
# environment: production # DELETE OR COMMENT THIS LINE
runs-on: ubuntu-latest
# Option B: Create environment in GitHub UI first
# Settings → Environments → New environment → "production"
# Configure protection rules as needed
Verify: Workflow runs without waiting for approval (unless you want it to).
Failure 6: Permissions Policy Too Restrictive
What happened: Role assumes successfully, but AWS API calls fail.
Error message:
AccessDenied: User: arn:aws:iam::123456789012:assumed-role/GitHubActionsOIDCRole/...
is not authorized to perform: s3:ListBucket on resource: arn:aws:s3:::your-lab-bucket-name
Why it happened: Trust policy allows assumption, but permissions policy doesn’t grant the needed actions. This is the “role assumes but can do nothing” scenario.
How to diagnose: Check CloudTrail for the AccessDenied event. The error message shows the missing permission.
The fix: Add the required permissions to the role’s permissions policy. For this lab:
{
"Action": ["s3:ListBucket", "s3:GetObject", "s3:PutObject"],
"Resource": ["arn:aws:s3:::your-lab-bucket-name", "arn:aws:s3:::your-lab-bucket-name/*"]
}
Verify: Re-run workflow. S3 operations should succeed.
Failure 7: Using StringEquals Instead of StringLike for sub
What happened: Trust policy looks correct but doesn’t match.
Error message:
AccessDenied: Not authorized to perform sts:AssumeRoleWithWebIdentity
Why it happened: StringEquals requires exact match. The sub claim includes the full ref path (refs/heads/main), not just the branch name (main).
Comparison:
// WRONG - StringEquals with partial value
"StringEquals": {
"token.actions.githubusercontent.com:sub": "repo:owner/repo:ref:main"
}
// CORRECT - StringLike with full pattern
"StringLike": {
"token.actions.githubusercontent.com:sub": "repo:owner/repo:ref:refs/heads/main"
}
// ALSO CORRECT - StringEquals with exact full value
"StringEquals": {
"token.actions.githubusercontent.com:sub": "repo:owner/repo:ref:refs/heads/main"
}
The fix: Use StringLike with the full sub pattern, or StringEquals with the exact full value from the token.
Verify: Re-run workflow.
Additional Troubleshooting Scenarios (From Documentation)
These are common failures documented by AWS and GitHub that I did not personally reproduce but are well-documented.
| Scenario | Cause | Fix |
|---|---|---|
| Thumbprint mismatch | GitHub rotated TLS cert, AWS has old thumbprint | Update provider: aws iam update-open-id-connect-provider --thumbprint-list NEW_THUMBPRINT |
| Token expired before use | Long-running job, token TTL exceeded | Tokens valid for 5 min; re-request if needed (action handles this) |
| Cross-account role assumption | Role in different account than OIDC provider | Trust policy must be in the target account; provider in same account |
| Forked repository runs | Fork sends different repository_owner claim |
Trust policy should restrict to repository_owner: YOUR_ORG |
| Reusable workflows | Caller/callee repository mismatch in sub |
Use github.workflow_repository context or adjust trust policy |
| Self-hosted runners | Different token endpoint behavior | Same OIDC flow works; ensure runner has internet access to token endpoint |
Security Hardening Checklist
After migration, verify each item:
- OIDC provider thumbprint is current (check GitHub docs annually)
- Trust policy restricts to specific repository (not
repo:*:*) - Trust policy restricts to specific branch/ref (not
repo:owner/repo:*unless intentional) - Trust policy includes
audcondition (sts.amazonaws.com) - Permissions policy follows least privilege (specific actions, specific resources)
- No long-lived AWS keys remain in GitHub Secrets (delete
AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY) - Workflow has minimal permissions (
id-token: write,contents: readonly) - GitHub Environment used for sensitive deployments (optional but recommended)
- Branch protection enabled on
main(prevents unauthorized workflow changes) - CloudTrail logging enabled (audit trail for assumed role usage)
Cleanup
When you’re done with the lab:
# 1. Delete role policy
aws iam delete-role-policy --role-name GitHubActionsOIDCRole --policy-name LeastPrivilegeS3Access
# 2. Delete role
aws iam delete-role --role-name GitHubActionsOIDCRole
# 3. Delete OIDC provider (only if no other roles use it)
aws iam delete-open-id-connect-provider --open-id-connect-provider-arn arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com
# 4. Remove GitHub Secrets (via UI or gh CLI)
gh secret delete AWS_ACCESS_KEY_ID
gh secret delete AWS_SECRET_ACCESS_KEY
gh secret delete AWS_REGION
Or use the provided cleanup.sh script from the downloadable bundle.
Comparison: Before vs After
| Aspect | Stored Keys (Before) | OIDC (After) |
|---|---|---|
| Credential lifetime | Years (until rotated) | 1 hour (auto-expires) |
| Rotation | Manual, often forgotten | Automatic, never needed |
| Scope | Works from anywhere | Only from specified repo/branch |
| Audit trail | Key ID only | Workflow run ID in session name |
| Secrets stored | 2-3 secrets | None |
| Leak impact | Full access until revoked | Expired credentials useless |
| Permission model | User’s full permissions | Role’s narrow permissions |
| Environment gating | Not possible | GitHub Environments + approvals |
FAQ
Q: Does this work with GitHub Enterprise Server?
Yes, but the OIDC endpoint URL differs. Use your GHES instance URL (e.g., https://github.yourcompany.com/_services/token). The thumbprint will also be different.
Q: Can I use this with other CI platforms?
Yes. GitLab, Azure DevOps, CircleCI, and others support OIDC. The trust policy sub claim format differs per platform — check their documentation.
Q: What if I need credentials for longer than 1 hour?
The aws-actions/configure-aws-credentials action automatically refreshes credentials. For custom scripts, use the AWS SDK’s default credential chain — it handles refresh transparently.
Q: Can a compromised workflow YAML steal the role?
If an attacker can modify the workflow YAML in your repository, they can run workflows that assume the role. This is why branch protection and CODEOWNERS on .github/workflows/ are critical. The OIDC token itself cannot be extracted and reused elsewhere due to the aud restriction.
Q: Does this work for pull requests from forks?
By default, no. Forked PRs run in the fork’s context with the fork’s repository_owner. To allow fork PRs, you’d need to adjust the trust policy (not recommended for production). Most teams run deployment workflows only on push to protected branches.
Q: What about Terraform/CloudFormation deployments?
Same pattern. The workflow assumes the role, then runs terraform apply or cfn deploy using the temporary credentials. The role needs permissions for the resources being managed.
Conclusion
Migrating from stored keys to OIDC is one of the highest-impact security improvements you can make to a CI/CD pipeline. The change is small — a trust policy, a role, and a workflow update — but it eliminates an entire class of credential leakage risks.
The failures I documented above are the ones you will hit. They’re not theoretical. The id-token: write permission, the sub claim format, the audience match — each one stops the pipeline cold until fixed. Now you know what to look for.
Download the lab bundle, run it in a test account, and break it yourself. That’s the only way to build confidence for production.
Official References
- GitHub Actions OIDC Overview
- GitHub OIDC with AWS
- AWS IAM OIDC Federation
- AWS STS AssumeRoleWithWebIdentity
- aws-actions/configure-aws-credentials
- AWS IAM Best Practices
Download the Lab Bundle
All working configurations from this article:
📦 OIDC Lab Download — Contains:
workflow-before.yml— Insecure stored-keys pipelineworkflow-after.yml— Secure OIDC pipelineiam-oidc-provider.json— OIDC provider referenceiam-role-trust-policy.json— Restricted trust policyiam-permissions-policy.json— Least-privilege permissionscleanup.sh— Automated cleanup scriptREADME.md— Full setup instructionsoidc-flow.mmd— Architecture diagram (Mermaid)
Internal links: This migration complements Ditching Long-Lived Access Keys (covers temporary credentials generally) and IAM Least Privilege (covers permission narrowing). The credential leakage risks are explored in Why Stolen Cloud Credentials Beat Software Bugs.