Overview and What You Will Learn
The most effective way to secure a CI/CD pipeline is to remove long-lived cloud credentials entirely. With OpenID Connect (OIDC), a job proves its identity to your cloud with a signed token and receives temporary credentials that expire on their own. Secrets that cannot be replaced this way, such as third-party API keys, belong in a managed secret store with rotation.
By the end of this topic you will be able to:
- Explain why static access keys in CI are a structural risk
- Configure GitHub Actions OIDC federation with an AWS IAM role, and outline the GCP equivalent
- Write a trust policy that limits a role to one repository and environment
- Scope workflow
permissionsand IAM policies to what a job actually needs - Mask derived secrets, pin third-party actions to a commit SHA, and keep an audit trail
Why This Matters in Production
A static cloud key stored as a repository secret never expires on its own, so anyone who obtains it keeps access until someone notices and rotates it. It can leak through a compromised laptop, a hijacked dependency, a debug step that prints the environment, or an over-shared secret store.
Platform teams at companies running hundreds of services, such as Stripe, Datadog, or PhonePe, cannot count on humans to rotate keys fast enough. OIDC changes the model: there is no stored cloud secret to steal, because each run requests a fresh credential that is valid for one hour by default and limited by the role's permissions.
Common MistakeSaving one AWS access key as a repository secret and reusing it across every workflow and environment. If that key leaks, the attacker has everything CI can do, until the key is found and revoked.
Core Principles
Why Static Credentials Are Dangerous
Static credentials have three structural problems. They do not expire on a useful schedule, they tend to be over-scoped because narrowing them is extra work, and they can be copied by anyone who can read the secret store or make a workflow print them.
How OIDC Federation Works
GitHub Actions can act as an identity provider. A running job asks GitHub for a signed JSON Web Token (JWT) that states facts such as the repository, the environment, and the workflow. Your cloud validates that token against a trust policy and returns temporary credentials. No secret is stored in GitHub.
The token's aud (audience) and sub (subject) claims are what the cloud checks. The sub value looks like repo:razorpay/payments-api:environment:production when the job uses a GitHub Environment, or repo:razorpay/payments-api:ref:refs/heads/main when it does not.
RememberA trust policy that is too loose is the main OIDC risk. Matching
repo:razorpay/*lets any workflow in any repository of the organization assume the role. Match the exact repository and environment.
Where to Keep the Secrets That Remain
Some values cannot be replaced by OIDC, such as a payment gateway sandbox key or a Slack webhook. Choose the store by blast radius and rotation needs:
- GitHub Secrets: fine for low-risk values, scoped to a repo or environment and encrypted at rest. They are not rotated automatically.
- AWS Secrets Manager: IAM-controlled access with built-in rotation, a natural fit once a job already has an OIDC role.
- HashiCorp Vault: dynamic short-lived secrets and a full audit log, useful when systems beyond CI need the same secrets.
TipIf a job already assumes an AWS role through OIDC, read runtime secrets from Secrets Manager inside the job instead of keeping a second copy in GitHub. You get one source of truth and one rotation point.
Least Privilege for Workflows and Roles
Grant each workflow only the token permissions it needs, and each IAM role only the actions on the resources that job touches. A job that pushes an image to ECR should not be able to delete S3 buckets.
permissions: contents: read jobs: deploy: runs-on: ubuntu-latest permissions: contents: read id-token: write # required to request an OIDC tokenPin Third-Party Actions to a Commit SHA
A tag such as @v4 can be moved by whoever controls the action's repository, so a compromised tag can run malicious code in your pipeline with your secrets. A full commit SHA is immutable.
# Risky: the tag can be repointed- uses: some-org/some-action@v4 # Safer: immutable commit, with the version in a comment for readers- uses: some-org/some-action@<full-40-character-commit-sha> # v4.1.0Look up the SHA behind a tag, then let Dependabot or Renovate propose updates so pins do not go stale:
gh api repos/actions/checkout/git/ref/tags/v4.1.6 --jq '.object.sha'# For an annotated tag this returns the tag object, so dereference it:gh api repos/actions/checkout/git/tags/<sha-from-above> --jq '.object.sha'Keep Secrets Out of Logs
CI platforms mask values stored as secrets, but only exact matches. A base64-encoded or concatenated value is not masked, so register derived values yourself. Pass secrets to scripts through env, not by pasting ${{ secrets.X }} into the script text, which also invites script injection.
- name: Mask a derived value env: API_KEY: ${{ secrets.API_KEY }} run: | DERIVED_TOKEN="${API_KEY}-${GITHUB_RUN_ID}" echo "::add-mask::$DERIVED_TOKEN" echo "token=$DERIVED_TOKEN" >> "$GITHUB_OUTPUT"SecurityNever run
envorprintenvas a debug step in a job that has secrets in its environment. It is one of the most common ways secrets end up in plaintext logs.
Audit Every Production Run
Production deploy jobs should leave a trail outside the CI platform: CloudTrail for the cloud API calls, plus a deployment record holding who triggered the run, the commit SHA, and the environment. The trail then survives even if CI history is deleted.
Detailed Step-by-Step Practical Lab
This lab lets the payments-api repository push an image to ECR and reach the mumbai-prod-cluster EKS cluster from GitHub Actions, with no AWS key stored in GitHub. Replace the account ID 123456789012 and names with yours.
Step 1 - Register GitHub as an OIDC Provider in AWS
This creates the trust anchor, once per AWS account. It does not yet allow any role to be assumed.
aws iam create-open-id-connect-provider \ --url https://token.actions.githubusercontent.com \ --client-id-list sts.amazonaws.com# Some CLI versions still ask for a thumbprint. AWS validates GitHub's# certificate through its trusted CA list, so the value is not used for trust.Step 2 - Create a Tightly Scoped IAM Role
The trust policy lets only the production environment of one repository assume the role. Use StringEquals for exact values, and keep the aud check.
{ "Version": "2012-10-17", "Statement": [ { "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", "token.actions.githubusercontent.com:sub": "repo:razorpay/payments-api:environment:production" } } } ]}Save it as trust-policy.json, then attach a permissions policy limited to pushing to one repository and describing one cluster:
{ "Version": "2012-10-17", "Statement": [ { "Sid": "EcrLogin", "Effect": "Allow", "Action": "ecr:GetAuthorizationToken", "Resource": "*" }, { "Sid": "EcrPushPaymentsApi", "Effect": "Allow", "Action": [ "ecr:BatchCheckLayerAvailability", "ecr:InitiateLayerUpload", "ecr:UploadLayerPart", "ecr:CompleteLayerUpload", "ecr:PutImage" ], "Resource": "arn:aws:ecr:ap-south-1:123456789012:repository/payments-api" }, { "Sid": "DescribeCluster", "Effect": "Allow", "Action": "eks:DescribeCluster", "Resource": "arn:aws:eks:ap-south-1:123456789012:cluster/mumbai-prod-cluster" } ]}aws iam create-role \ --role-name gha-payments-api-deploy-role \ --assume-role-policy-document file://trust-policy.json aws iam put-role-policy \ --role-name gha-payments-api-deploy-role \ --policy-name payments-api-deploy \ --policy-document file://permissions-policy.jsonTip
eks:DescribeClusteronly lets the job fetch cluster details. What the job may do inside Kubernetes is controlled separately by an EKS access entry or RBAC binding for the role, which you should also scope to the one namespace it deploys to.
Step 3 - Assume the Role From the Workflow
The job needs id-token: write and an environment that matches the trust policy. After the credentials step, aws sts get-caller-identity should print the assumed role, not an IAM user.
name: Deploy payments-api to production on: push: branches: [main] permissions: contents: read jobs: deploy: runs-on: ubuntu-latest environment: production # must match the sub claim in Step 2 permissions: contents: read id-token: write steps: - uses: actions/checkout@<full-commit-sha> # v4.x.x - name: Configure AWS credentials via OIDC uses: aws-actions/configure-aws-credentials@<full-commit-sha> # v4.x.x with: role-to-assume: arn:aws:iam::123456789012:role/gha-payments-api-deploy-role aws-region: ap-south-1 - name: Verify identity run: aws sts get-caller-identityBecause the job uses an environment, protect that environment in the repository settings: require reviewers and restrict deployments to the main branch. The OIDC subject then proves "production environment", and GitHub enforces who can reach it.
Step 4 - Push the Image and Reach the Cluster
Everything here uses credentials that expire when the job ends.
- uses: aws-actions/amazon-ecr-login@<full-commit-sha> # v2.x.x id: ecr - name: Build and push env: REGISTRY: ${{ steps.ecr.outputs.registry }} run: | docker build -t "$REGISTRY/payments-api:${GITHUB_SHA}" . docker push "$REGISTRY/payments-api:${GITHUB_SHA}" - name: Point kubectl at the cluster run: aws eks update-kubeconfig --name mumbai-prod-cluster --region ap-south-1Step 5 - Pin Every Action and Mask Derived Values
Replace every tag reference with a full commit SHA and a version comment, as shown in Core Principles. Add ::add-mask:: for any value derived from a secret before you echo it or write it to GITHUB_OUTPUT. Enable Dependabot for the github-actions ecosystem so the pins get update pull requests.
Step 6 - Confirm the Audit Trail
CloudTrail records the role assumption and the API calls that follow. Events can take several minutes to appear.
aws cloudtrail lookup-events \ --lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleWithWebIdentity \ --max-results 5 \ --query 'Events[].[EventTime,Username]' --output tableLook for the role session created by your workflow run, followed by the ECR calls from the same session. This is your answer to "what did CI do and when".
Step 7 - Outline GCP Workload Identity Federation
On Google Cloud the same idea uses a workload identity pool. The attribute condition is what restricts access to one repository.
gcloud iam workload-identity-pools create gha-pool \ --location=global --display-name="GitHub Actions" gcloud iam workload-identity-pools providers create-oidc gha-provider \ --location=global --workload-identity-pool=gha-pool \ --issuer-uri="https://token.actions.githubusercontent.com" \ --attribute-mapping="google.subject=assertion.sub,attribute.repository=assertion.repository" \ --attribute-condition="assertion.repository=='razorpay/payments-api'" gcloud iam service-accounts add-iam-policy-binding \ deploy-sa@mumbai-prod-project.iam.gserviceaccount.com \ --role=roles/iam.workloadIdentityUser \ --member="principalSet://iam.googleapis.com/projects/123456789012/locations/global/workloadIdentityPools/gha-pool/attribute.repository/razorpay/payments-api"Production Best Practices & Common Pitfalls
- Scope the trust policy tightly. Match the exact repository and environment, and where possible the workflow file through the
job_workflow_refclaim. Never leavesubas a wildcard. - Use separate roles per environment. The role a staging job assumes must not carry production permissions.
- Rotate the secrets OIDC cannot replace. Put third-party keys on a schedule, ideally automated by a secret manager.
- Keep the default token read-only. Set the organization default for
GITHUB_TOKENto read-only and grant write access per job. - Treat fork pull requests as untrusted. Do not expose secrets to them, and avoid
pull_request_targetwith code checked out from the fork. - Audit pinning. Run a lint workflow that fails when a new action is referenced by tag instead of SHA. Recent GitHub versions also offer an organization policy that requires full-length SHA pins.
- Never use
permissions: write-all. Declare only what each job needs.
Common MistakeSetting a trust policy
subto a branch ref while the job runs in a GitHub Environment. With an environment, thesubclaim containsenvironment:<name>instead of the branch, so the match fails withNot authorized to perform sts:AssumeRoleWithWebIdentity.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
aws sts get-caller-identity |
Show the identity the job is using |
aws iam get-role --role-name <name> |
Inspect a role's trust policy |
aws cloudtrail lookup-events |
Review role assumptions and API calls |
gh api repos/<owner>/<repo>/git/ref/tags/<tag> |
Find the commit behind an action tag |
gh secret list |
List secrets without exposing values |
| Symptom | Likely Cause | Fix |
|---|---|---|
Not authorized to perform sts:AssumeRoleWithWebIdentity |
sub or aud does not match |
Compare the token's sub with the trust policy |
| OIDC token request fails | id-token: write missing |
Add it at job or workflow level |
| Secret visible in logs | Derived value never masked | Add ::add-mask:: before printing |
| Action changed behaviour overnight | Referenced by a moved tag | Pin to a commit SHA |
| Staging job can reach production | Shared role across environments | Create one role per environment |