Keyless CI and rotating credentials without an outage
Replace long-lived cloud keys in CI with short-lived OIDC credentials and an IAM trust policy, then rotate a database password by running two users side by side before you drop the old one.
Contentsand lesson path
On this page
- Keyless deploys with OpenID Connect
- Worked Example: Rotating a Database Password Without an Outage
- Check your understanding
- Apply it
- Review prompt
Lessons of Secrets Management
- How secrets escape, and what to do when one does Concept · 20 min
- Lab: scan a repository and an image for leaked credentials Lab · 20 min
- Secret managers and the path from store to process Concept · 15 min
- Lab: sync a secret from a manager into Kubernetes Lab · 30 min
- Keyless CI and rotating credentials without an outage Worked example · 25 min
- Check: secrets design review Knowledge check · 6 questions
What you will learn
- Replace long-lived CI and cloud keys with OIDC workload identity federation and short-lived credentials, and rotate a secret without downtime.
01. Keyless deploys with OpenID Connect
For over a decade, continuous integration (CI) pipelines deployed cloud infrastructure by storing long-lived, static credentials (such as AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY) inside repository secret vaults. This was risky: static keys rarely expired, they were frequently granted broad administrator permissions, and if a malicious dependency or workflow compromised the CI runner, the attacker kept cloud access until someone noticed and rotated the key.
Current practice replaces static keys with Keyless CI via OpenID Connect (OIDC) Workload Identity Federation. In an OIDC architecture, no cloud credentials of any kind are stored in GitHub, GitLab, or CircleCI:
-
Token Minting: When a deployment workflow runs, the CI runner requests an ephemeral JSON Web Token (OIDC JWT) signed by GitHub's cryptographic identity provider using the runner's local environment (
ACTIONS_ID_TOKEN_REQUEST_URLandACTIONS_ID_TOKEN_REQUEST_TOKEN). The job can request the token only if itspermissionsincludeid-token: write; that permission allows nothing else, and because listing any permission sets the others tonone, the job also listscontents: read. -
Federated Role Exchange: The workflow sends this JWT to the cloud provider's Security Token Service (e.g. AWS STS
AssumeRoleWithWebIdentity, Google Cloud Workload Identity Federation, or Azure Federated Credentials). -
Cryptographic Validation: The cloud provider verifies the digital signature against GitHub's OpenID discovery endpoint (
https://token.actions.githubusercontent.com/.well-known/openid-configuration), checking public keys via JSON Web Key Sets (JWKS). -
Short-Lived Session: If the token's claims match the role's trust policy, STS returns temporary credentials. They stay valid for the session length the job asked for, not until the deployment finishes:
configure-aws-credentialsasks for one hour unless you setrole-duration-seconds(900 is 15 minutes), and the role's maximum session duration, one hour unless an administrator raises it to at most 12 hours, caps the request. They are bearer credentials: anyone who copies them out of the job can use them from anywhere, with the role's permissions, until they expire. That is why sessions are kept short and roles narrow.
The security boundary of OIDC federation relies on granular claim validation embedded in the JWT payload:
iss(Issuer): Identifies the trusted token mint (https://token.actions.githubusercontent.com).aud(Audience): Proves the token was requested specifically for the cloud provider (e.g.sts.amazonaws.com).sub(Subject): Pinned to the exact repository, Git reference, and environment (e.g.repo:acme/payment-service:environment:production).job_workflow_ref: Names the workflow file that is running and the ref it ran from (for a reusable workflow,org/shared/.github/workflows/deploy.yml@refs/tags/v1). A ref can move; the exact commit is in the separatejob_workflow_shaclaim, so trust policies that must pin the code check that claim too.
name: Production Deploy
on:
push:
branches: [main]
permissions:
contents: read
jobs:
deploy:
runs-on: ubuntu-latest
# The environment name goes into the token: the sub claim becomes
# repo:acme/payment-service:environment:production
environment: production
permissions:
contents: read
id-token: write # lets this job request the OIDC token; it grants no repo writes
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Configure AWS Credentials via OIDC
# v6.3.1. Split only to fit this page. In double quotes, a trailing `\`
# drops the line break and the next line's leading spaces; without it
# YAML puts a space after "@" and the ref breaks. In a real workflow keep
# the value and its `# vX.Y.Z` tag comment on one line, so audits and
# Dependabot/Renovate see the pin.
uses: "aws-actions/configure-aws-credentials@\
45666896f5d8e0f10ae255413f3a4cdd03bdc8f5"
with:
role-to-assume: arn:aws:iam::123456789012:role/github-deployer
aws-region: us-east-1
audience: sts.amazonaws.com
role-duration-seconds: 900 # 15 minutes; without it the action asks for 1 hour
- name: Deploy to Kubernetes
run: |
aws eks update-kubeconfig --name payments-prod --region us-east-1
kubectl apply -k k8s/overlays/prodThe other half lives in AWS: the IAM role's trust policy, the document that says who may assume the role. It trusts GitHub's OIDC provider (registered once per AWS account) and allows sts:AssumeRoleWithWebIdentity only when two claims match exactly. aud must be sts.amazonaws.com, the audience the action requests. sub must name this repository and the production environment. Because the job sets environment: production, GitHub builds its sub from the environment instead of the branch; remove that line and the same job gets repo:acme/payment-service:ref:refs/heads/main, which this policy rejects. The environment also lets you add protection rules, such as required reviewers or a list of branches allowed to deploy. For repositories created after 15 July 2026, or that opted in, GitHub adds the owner and repository IDs to sub (for example repo:acme@123456/payment-service@456789:environment:production), and renamed or transferred repositories move to that format too, so check which format your repository uses before you copy a policy.
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "sts:AssumeRoleWithWebIdentity",
"Principal": {
"Federated":
"arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com"
},
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
"token.actions.githubusercontent.com:sub":
"repo:acme/payment-service:environment:production"
}
}
}]
}You can check the matching logic locally before touching AWS. The script below applies the policy's StringEquals block to three sample sets of claims: the job as written, the job without environment:, and a workflow in another repository. It imitates the comparison only; it does not call AWS.
"""Check sample token claims against the StringEquals block of trust-policy.json."""
import json
with open("trust-policy.json") as f:
want = json.load(f)["Statement"][0]["Condition"]["StringEquals"]
prefix = "token.actions.githubusercontent.com:"
samples = [
# the deploy job above, which sets environment: production
{"aud": "sts.amazonaws.com",
"sub": "repo:acme/payment-service:environment:production"},
# the same job with the environment: line removed
{"aud": "sts.amazonaws.com",
"sub": "repo:acme/payment-service:ref:refs/heads/main"},
# a workflow in someone else's repository
{"aud": "sts.amazonaws.com",
"sub": "repo:mallory/payment-service:environment:production"},
]
for claims in samples:
ok = all(claims[key.removeprefix(prefix)] == value for key, value in want.items())
print("ALLOW" if ok else "DENY ", claims["sub"])$ python3 check_trust.py
ALLOW repo:acme/payment-service:environment:production
DENY repo:acme/payment-service:ref:refs/heads/main
DENY repo:mallory/payment-service:environment:production02. Worked Example: Rotating a Database Password Without an Outage
Many teams must rotate production database passwords on a schedule, for example to meet a compliance rule. A naive rotation changes the password in PostgreSQL and the secret in Vault at the same moment. Connections that are already open keep working, but any pod that reconnects or starts with the old password before it receives the new one fails to log in, so the service starts failing during the rollout.
The dual-credential overlap pattern closes that login gap by keeping both passwords valid during the rollout. It has seven steps:
-
Step 1 (Provision Secondary Account): Create a second database user (
db_user_v2) in PostgreSQL with a fresh, cryptographically generated password, granting it identical schema permissions asdb_user_v1. -
Step 2 (Update Secret Manager): Update the secret in HashiCorp Vault or AWS Secrets Manager to reference
db_user_v2and its new password. -
Step 3 (Reconcile Kubernetes Secret): External Secrets Operator reconciles the change based on
refreshInterval, updating the target Kubernetes Secret; running Pods are not touched yet. -
Step 4 (Rolling Update Deployment): Trigger a rolling update of the application (
kubectl rollout restart deployment/web-service). -
Step 5 (Dual-Connection Overlap): As new Pods start, they connect to the database using
db_user_v2. Existing Pods continue processing in-flight transactions usingdb_user_v1. Because both credentials are valid at the same time, authentication does not fail during the rollout. Requests can still fail for other reasons, such as pods that are killed without draining, so the rollout itself must drain connections gracefully. -
Step 6 (Verify Connection Draining): Query database connection metrics (
pg_stat_activity) until active sessions ondb_user_v1drop to zero. -
Step 7 (Revoke Deprecated Account): Only after
pg_stat_activityshows no sessions fordb_user_v1and your pools have recycled, retire it.REVOKE ALL ON DATABASEplusDROP USERis not enough when the old user owns tables (common when migrations ran as the application user):DROP ROLEthen fails with "role cannot be dropped because some objects depend on it". UseREASSIGN OWNED BYandDROP OWNED BYfirst, and better still, let aNOLOGINowner role own the tables so application users never own anything.
Connection pools matter here. Pools such as HikariCP in Java, pgxpool or database/sql in Go, and SQLAlchemy in Python keep connections open for a long time, and each connection stays logged in as the user it opened with. A maximum connection lifetime, for example HikariCP maxLifetime: 1800000 (30 minutes) and idleTimeout: 600000 (10 minutes), makes the pool replace old connections by itself, so they move to db_user_v2 without killing processes.
Automated rotation platforms take over these steps. An AWS Secrets Manager rotation Lambda function runs four steps, createSecret, setSecret, testSecret and finishSecret; if a step fails, Secrets Manager retries it or stops at that step so you can investigate, and the current secret version stays in place until finishSecret moves the label. HashiCorp Vault's database secrets engine works differently: with dynamic secrets it creates a new short-lived database user for each lease and drops it when the lease expires, so there is no shared password to rotate at all.
Never put the new password in a script file. The scripts below read it from a psql variable set on the command line, and you write the same value straight to the secret manager. Run them from a trusted admin host: the value is briefly visible in that host's process list, and PostgreSQL writes it to the server log if log_statement is ddl or all.
-- Step 1, run before the rollout. The password comes from outside the file:
-- NEW_PW="$(openssl rand -base64 32)"
-- psql -v ON_ERROR_STOP=1 -v pw="$NEW_PW" -f scripts/rotate-1-create.sql
-- then store "$NEW_PW" in the secret manager. Never commit a password.
CREATE ROLE db_user_v2 LOGIN PASSWORD :'pw';
GRANT CONNECT ON DATABASE app_prod TO db_user_v2;
GRANT app_readwrite TO db_user_v2;-- Steps 6 and 7, run after every pod uses db_user_v2 and pools have recycled:
-- psql -v ON_ERROR_STOP=1 -f scripts/rotate-7-retire.sql
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM pg_stat_activity WHERE usename = 'db_user_v1') THEN
RAISE EXCEPTION 'db_user_v1 still has sessions';
END IF;
END $$;
-- Hand anything v1 owns (tables created by migrations) to the owner role,
-- then remove its remaining grants and the role itself.
REASSIGN OWNED BY db_user_v1 TO app_owner; -- app_owner: a NOLOGIN owner role
DROP OWNED BY db_user_v1; -- run both in each DB where v1 owns objects or has grants
DROP ROLE db_user_v1;$ psql -v ON_ERROR_STOP=1 -f scripts/rotate-7-retire.sql; echo "exit: $?"
psql:scripts/rotate-7-retire.sql:8: ERROR: db_user_v1 still has sessions
CONTEXT: PL/pgSQL function inline_code_block line 4 at RAISE
exit: 3
$ psql -v ON_ERROR_STOP=1 -f scripts/rotate-7-retire.sql; echo "exit: $?"
DO
REASSIGN OWNED
DROP OWNED
DROP ROLE
exit: 003. Check your understanding
04. Apply it
Implement these keyless CI and rotation standards across your delivery pipelines:
- Migrate CI to OIDC Federation: Replace static AWS, GCP, and Azure service account keys in CI with OpenID Connect role assumption.
- Pin the OIDC Subject Claim: Always restrict IAM trust policies to specific repositories and environments (
repo:org/app:environment:prod). - Adopt Dual-Credential Rotation: Practice dual-user rotation so passwords can be changed without severing active client connections.
- Tune Connection Pool Lifetimes: Configure client database connection pool maxLifetime and idleTimeout to naturally drain and recycle old sockets before decommissioning credentials.
- Monitor Database Session Draining: Verify active database connection metrics before dropping legacy user accounts.
- Set Token Session Limits: Request the shortest session the deployment needs with
role-duration-seconds(900 is the minimum, 15 minutes) and keep the role's maximum session duration low. - Alert on Unpinned Role Assumptions: Audit cloud IAM logs via AWS CloudTrail or Google Cloud Audit Logs to flag any role assumption events that lack matching subject claims.
- Automate Rotation Verification: Test automated credential rotation regularly in staging and check that workloads reconnect without restarts.
05. Review prompt
Explain how OpenID Connect (OIDC) Workload Identity Federation replaces static cloud access keys in continuous integration pipelines with temporary, short-lived tokens. Write the two StringEquals conditions of the trust policy from memory, say what changes in sub when the job sets environment:, and what decides how long the issued credentials stay valid. Then outline the dual-credential procedure for rotating a database password while Kubernetes workloads keep serving traffic.
References
- OWASP Secrets Management Cheat Sheet
- HashiCorp Vault Documentation
- PostgreSQL documentation: Dropping roles
- AWS Secrets Manager: Rotation by Lambda function
- Vault Docs: Database secrets engine
- GitHub Docs: Configuring OpenID Connect in Amazon Web Services
- GitHub Docs: OpenID Connect reference (subject claims, immutable subjects)
- aws-actions/configure-aws-credentials (role-duration-seconds and other inputs)
- AWS STS API Reference: AssumeRoleWithWebIdentity (DurationSeconds)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.