Skip to content
Derar Sattouf

Secrets Management in 2026: Vault, SOPS and Workload Identity

Updated Security

Secrets Management in 2026: Vault, SOPS and Workload Identity

Every production incident report about a leaked credential reads the same way. A key was committed to a repository, pasted into a chat, baked into an image, printed in a CI log, or left in a .env file on a laptop. It lived for months. Nobody knew who used it, so nobody dared rotate it. Then someone else found it first.

Secrets management is the discipline of making that story impossible, or at least short. The modern answer has three layers. First, do not have static secrets where you can avoid them: use workload identity and OIDC federation so that a pipeline or a pod proves who it is and receives short-lived credentials. Second, where you must have secrets, keep them in a purpose-built system (a cloud secret manager, Vault or OpenBao, or encrypted files with SOPS) with access control, audit logs and rotation. Third, assume leaks will happen and build detection, revocation and a rehearsed playbook.

Start by eliminating static credentials. Use OIDC federation (GitHub Actions to AWS, GCP, Azure), IAM roles for service accounts (IRSA), EKS Pod Identity, GKE Workload Identity Federation, and Azure Workload Identity. No long-lived key means nothing to leak. Prefer dynamic, short-lived secrets (Vault database credentials, STS tokens) over static ones, because a leaked 15-minute credential is a small incident.

For the secrets that remain (third-party API keys, database passwords, signing keys), use a secret manager: AWS Secrets Manager or Parameter Store, GCP Secret Manager, Azure Key Vault, or HashiCorp Vault and its open source fork OpenBao for dynamic secrets. Git is not a secret store, with one exception: encrypted files with SOPS plus age (or a cloud KMS) are a good fit for GitOps repositories. In Kubernetes, sync from a manager with the External Secrets Operator or the Secrets Store CSI Driver, and encrypt Kubernetes Secrets at rest in etcd. Remember that base64 is not encryption.

Scan everything: pre-commit hooks, CI scans with gitleaks or TruffleHog, host-side push protection, and history scans. Scanning finds secrets; it does not make them safe. When a secret leaks, revoke first and investigate second: rotate, check audit logs for use, and remove it from history only after the rotation, because history rewriting does not un-leak anything. Design for rotation from day one, with two active versions, graceful reload and no redeploy needed.

AI agents and MCP servers are new secret consumers. Give them scoped, short-lived credentials, keep secrets out of prompts and tool arguments, and never let the model see the raw secret. And pair every secret with an owner, a purpose, an expiry and an audit trail, because an unowned secret is a liability.

This pairs with OWASP Top 10 for Developers (cryptographic failures and supply chain) and OAuth 2.1 and OIDC: Common API Security Pitfalls, whose token concepts underpin workload identity.

Tool names, action versions, flags and pricing change, so where a detail is likely to drift the text says "verify against current docs". The concepts are stable; copy the structure, then confirm syntax against the vendor documentation linked at the end.

Which tool should I use?

SituationRecommended approach
Single cloud, a few servicesThe cloud's native secret manager plus IAM-based access
Multi-cloud or on-prem, need dynamic DB credentials, PKI, or SSH signingVault or OpenBao
GitOps repository with Kubernetes manifestsSOPS with age or KMS, or External Secrets Operator with no secrets in Git
CI/CD to cloudOIDC federation, no stored cloud keys
Kubernetes pod to cloud APIWorkload identity (IRSA, Pod Identity, GKE WIF, Azure Workload Identity)
Small team, one VPSSOPS plus age, or a managed secret service; avoid hand-edited .env on servers
Third-party API key that cannot rotate automaticallySecret manager with scheduled rotation reminders and a documented procedure
Local developmentA dev-only secret per developer from a manager CLI, or encrypted dotenv, never production values

What counts as a secret

A secret is any value that grants access or proves identity, and whose disclosure causes harm. The obvious ones get attention. The less obvious ones cause the breaches.

CategoryExamplesNotes
CredentialsDatabase passwords, SMTP passwords, service account passwordsPrefer IAM auth where the database supports it
API keys and tokensStripe secret keys, OpenAI or Anthropic API keys, GitHub tokens, Slack bot tokensScope them narrowly; many providers offer restricted keys
Cloud credentialsAWS access keys, GCP service account JSON keys, Azure client secretsThe highest-value target; replace with federation
Cryptographic keysTLS private keys, JWT signing keys, SSH private keys, age or GPG keys, encryption data keysKeep in KMS or HSM where possible
Session and signing secretsCookie secrets, CSRF secrets, webhook signing secretsRotation invalidates sessions, plan for it
Connection stringsAnything with user:password@host embeddedOften missed by scanners
Infrastructure secretsTerraform state (contains secrets), kubeconfig, Docker registry credentialsState files and kubeconfigs are frequently overlooked
Personal tokensDeveloper PATs, npm and PyPI publish tokensLong-lived, powerful, and attached to humans
Derived or session dataShort-lived access tokens, presigned URLsLower risk, but still treat as sensitive in logs

Things that are not secrets but are often handled as if they were: public client IDs, publishable keys (Stripe pk_, Firebase web config), public keys, feature flags, and non-sensitive configuration. Misclassifying them creates noise that trains people to ignore real alerts. Separate configuration (safe to commit, differs per environment) from secrets (never committed in plaintext).

The secret lifecycle

 Generate -> Store -> Distribute -> Use -> Rotate -> Revoke -> Destroy
    |          |          |          |        |         |          |
 strong     manager   identity-    memory   scheduled  on leak   delete
 random     + ACL     based        only     or event   or exit   versions
 (CSPRNG)   + audit   delivery     no logs  driven     fast      + audit

Every stage has a failure mode:

StageTypical failureControl
GenerateHuman-chosen or reused passwordsGenerate randomly with at least 128 bits of entropy; one secret per purpose
StorePlaintext in repo, wiki, chat, tickets, shared drivesSecret manager, SOPS, or KMS-encrypted store
DistributeEmailing a password, passing through CI logsPull-based, identity-authenticated delivery
UseLogged, put in command-line arguments, visible in ps or crash dumpsEnvironment or file with tight permissions, log redaction
RotateNever done; fear of breaking thingsDual-version support, automation, game days
RevokeDo not know where the secret is usedInventory and audit logs; one purpose per secret
DestroyOld versions linger in backups and historyRetention policy, version deletion, backup expiry

The single most useful property is knowing what uses a secret. If you can answer "who and what reads this secret" in one query, rotation and revocation are routine. If you cannot, every leak becomes a crisis.

The problem with .env files, CI variables and "just env vars"

.env files are fine as a developer convenience for non-sensitive local settings. As the production secret mechanism they have predictable problems.

ProblemHow it bites
Copied everywhereOne file becomes ten copies on laptops, servers, backups, screenshots, and chat history
No access controlAnyone who can read the file or the process environment has everything
No auditYou cannot tell who read a value or when
No rotation storyChanging a value means editing files on every machine and restarting
Accidentally committedMissing .gitignore entry, a renamed file, a .env.production nobody ignored
Baked into imagesCOPY . . includes the .env; layers keep it forever
Leaks via process listingEnvironment variables are visible to same-user processes, crash reporters and debug endpoints
Leaks via logsFrameworks dump the environment in error pages; docker inspect shows env vars

The Docker image trap

# BAD: secret is baked into a layer even if you delete it later
FROM node:22-slim
WORKDIR /app
COPY . .
ARG NPM_TOKEN
RUN echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc && npm ci && rm .npmrc

The ARG value and the file are recoverable from the image history. Use a BuildKit secret mount instead, which never lands in a layer:

# GOOD: secret exists only during that RUN step
# syntax=docker/dockerfile:1
FROM node:22-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
COPY . .
docker build --secret id=npmrc,src=$HOME/.npmrc -t myapp:ci .

Also add a .dockerignore that excludes .env*, *.pem, .git, and credentials directories.

CI secrets

Repository or organization secrets in GitHub Actions, GitLab CI variables and similar are encrypted at rest and masked in logs, which is a decent baseline, but they have limits:

  • They are long-lived static values that any workflow with access can read.
  • Log masking is pattern-based. A transformed secret (base64, URL-encoded, split across lines) is not masked.
  • Pull requests from forks, pull_request_target, third-party actions, and compromised dependencies are all routes to exfiltration.
  • They are hard to audit: you see that the secret was injected, not what it did.

The rule of thumb: use CI secrets for third-party tokens you cannot federate, and use OIDC for anything in your own cloud. Scope secrets to environments with required reviewers, and never expose them to untrusted code paths. See the section on workload identity and OIDC federation.

Environment variables: use with care

Env vars are the lowest-common-denominator interface and are fine as the final hop (the platform injects them from a manager into the process). The risks are in how they get there and what else can read them. Where the platform supports it, prefer files on a tmpfs (Kubernetes secret volumes, Docker and Compose secrets, systemd LoadCredential) because they can have restrictive permissions, are not inherited by child processes, and do not appear in docker inspect.

Secret scanning: pre-commit, CI, push protection and history

Scanning is detective and preventive. Run it at four points.

developer laptop        pre-commit hook (gitleaks / trufflehog)      -> fastest feedback
git host                push protection (GitHub, GitLab)             -> blocks the push
CI                      gitleaks / trufflehog on the diff            -> backstop, covers other hosts
scheduled               full-history and org-wide scans              -> finds the old stuff

gitleaks

# .gitleaks.toml
title = "project gitleaks config"

[extend]
useDefault = true

[[rules]]
id = "internal-service-token"
description = "Internal service token"
regex = '''svc_[A-Za-z0-9]{32}'''
keywords = ["svc_"]

[allowlist]
description = "Test fixtures and docs"
paths = [
  '''docs/.*''',
  '''tests/fixtures/.*''',
]
regexes = ['''EXAMPLE_NOT_A_REAL_KEY''']
# .pre-commit-config.yaml
repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.x.y   # pin to a current release tag; verify the latest
    hooks:
      - id: gitleaks
# Scan the working tree and the full history, redacting values in output
gitleaks detect --source . --redact --verbose
# Scan only staged changes (what a pre-commit hook does)
gitleaks protect --staged --redact

Subcommand names have changed between gitleaks releases; run gitleaks --help and verify against current docs.

TruffleHog

TruffleHog's differentiator is verification: it can test whether a detected credential is still live against the provider, which cuts triage time.

trufflehog git file://. --only-verified --fail
trufflehog github --org=my-org --only-verified      # org-wide, needs a read token
trufflehog filesystem ./build --only-verified

Scan more than Git: container images (trufflehog docker --image ...), build artifacts, S3 buckets and Slack exports are all places where secrets hide.

Platform push protection

GitHub secret scanning with push protection blocks pushes that contain recognized provider tokens, and partner providers are notified to revoke their own leaked tokens. GitLab has comparable secret push protection. Enable them organization-wide. Verify the current feature set and plan availability in the host's docs, because some features depend on plan and visibility.

CI backstop

# .github/workflows/secrets-scan.yml
name: secrets-scan
on: [pull_request]
permissions:
  contents: read
jobs:
  gitleaks:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          persist-credentials: false
      - name: gitleaks
        run: |
          docker run --rm -v "$PWD:/repo" zricethezav/gitleaks:latest \
            detect --source /repo --redact --exit-code 1 \
            --log-opts="origin/${{ github.base_ref }}..HEAD"

Scanning limits

  • Entropy-based detection has false positives; regex detection has false negatives. Use both.
  • Scanners miss passwords (no recognizable shape), custom internal tokens (add rules), and encoded or split values.
  • Finding a secret in history means it is compromised. Cleaning history is cosmetic.
  • Baseline existing findings, fix them, then block new ones. A scanner that fails on 400 historic findings gets disabled.

A secret leaked: the rotation playbook

When a secret is exposed, speed beats elegance. The order matters.

T+0     DETECT      scanner alert, provider notification, a report, a log search
T+5m    CONTAIN     revoke or disable the credential at the provider (or deny via policy)
T+15m   ROTATE      issue a replacement; deploy it through the normal secret path
T+30m   ASSESS      audit logs: was it used? from where? what did it access?
T+1h    ERADICATE   remove from code/history/artifacts; fix the root cause
T+1d    RECOVER     verify services healthy; widen monitoring for the identity
T+1w    LEARN       blameless post-incident review; add a preventive control

Step by step

  1. Revoke before you investigate. The reflex is to first work out who committed it. Resist. Disable or rotate the credential immediately. If rotation would cause an outage, first apply a compensating control (an IP allow-list, a deny policy, a temporary rate limit) and rotate inside minutes, not days.
  2. Treat the secret as burned, even if the repository is private, the commit was reverted, or the push was blocked after the fact. Bots scrape public pushes within seconds; private repositories can be cloned, forked, or opened up later.
  3. Pull audit logs for the credential's window of exposure: AWS CloudTrail, GCP Cloud Audit Logs, Azure Activity and Entra sign-in logs, database audit logs, provider dashboards. Look for unfamiliar IPs, regions, user agents, and unusual API calls such as listing buckets, creating users, spinning up compute (cryptomining is common), or disabling logging.
  4. Scope the blast radius. What could this credential do? Data read, data written, resources created, other credentials obtainable (an IAM role that can read other secrets means those are also burned).
  5. Remove the secret from the source (code, config, wiki, chat export) and from artifacts (container images, build logs, package registries). Only after rotating, rewrite history with git filter-repo or BFG if policy demands it, and tell everyone to re-clone. Remember forks and caches may keep copies.
  6. Fix the cause. Why was it in the code? No manager available, a bad example in the README, a test that needed a real key, a missing hook? Add the control that would have stopped this.
  7. Notify according to your obligations. Customer data exposure may trigger legal notification windows (for example under GDPR). Involve the security or legal contact early. Do not guess at the law; verify with your counsel.
  8. Document the timeline, evidence, and actions.

Provider quick reference

SecretWhere to revokeNotes
AWS access keyIAM, deactivate then delete the key; check CloudTrailAlso check for newly created keys, roles and users
GCP service account keyIAM, delete the key; consider disabling the service accountCheck Cloud Audit Logs for the key ID
Azure client secretEntra ID app registration, delete the secretReview sign-in logs for the service principal
GitHub PAT or app tokenSettings, revoke; for apps, rotate the private key or secretReview the audit log
Stripe, Twilio, SendGrid, etc.Provider dashboard, roll the keyMany support rolling with a grace period
Database passwordChange password; terminate existing sessionsCheck for new users, extensions, exfil queries
JWT signing keyRotate with a key ID (kid) overlap; invalidate sessions if compromise is likelyRequires verifiers to support multiple keys
SSH keyRemove from authorized_keys and host provider settingsAudit logins
npm or PyPI tokenRevoke at the registry; review recently published versionsA compromised publish token is a supply chain incident

A runbook script skeleton

Keep a tested script for your most common credential types, and rehearse it. This example shows an AWS access key containment sequence; adapt and test in a sandbox account.

#!/usr/bin/env bash
# contain-aws-key.sh  ACCESS_KEY_ID USER_NAME
set -euo pipefail
KEY_ID="$1"; USER_NAME="$2"

# 1. Deactivate (reversible) rather than delete, to keep evidence and allow rollback
aws iam update-access-key --user-name "$USER_NAME" --access-key-id "$KEY_ID" --status Inactive

# 2. Capture recent activity for this key (CloudTrail lookups are limited to 90 days of management events)
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=AccessKeyId,AttributeValue="$KEY_ID" \
  --max-results 50 --output json > "evidence-${KEY_ID}.json"

# 3. List what the user can do, to scope blast radius
aws iam list-attached-user-policies --user-name "$USER_NAME"
aws iam list-user-policies --user-name "$USER_NAME"
aws iam list-groups-for-user --user-name "$USER_NAME"

Common mistakes during a leak

  • Deleting the commit and calling it fixed.
  • Rotating one key but not its siblings (staging, other regions, other services that shared it).
  • Forgetting the secret also lives in CI variables, Terraform state, Docker layers, and local .env files.
  • Skipping the audit log review because "it was only exposed for a minute".
  • Announcing in a public channel with the secret still quoted in the message.

A practical drill

Run a quarterly secret rotation game day: pick a non-critical credential, declare it leaked, and time the steps from detection to confirmed rotation. The first run reveals every hidden copy of the secret. Track the time and drive it down.

Cloud secret managers

All three major clouds provide a managed secret store with encryption, IAM, versioning and audit logs. They are the right default for most teams.

Comparison

FeatureAWS Secrets ManagerAWS SSM Parameter StoreGCP Secret ManagerAzure Key Vault
Primary useSecrets with rotationConfig and secrets (SecureString)SecretsSecrets, keys, certificates
VersioningYes, with staging labels (AWSCURRENT, AWSPENDING)YesYes, numbered versions and aliasesYes
Built-in rotationYes (Lambda-based, with managed rotation for some services)No (DIY)Rotation notifications via Pub/Sub; you implement rotationRotation policy for keys; secrets by event plus automation
EncryptionKMSKMS for SecureStringGoogle-managed or CMEKSoftware or HSM-backed
Access controlIAM and resource policiesIAMIAMAzure RBAC (recommended) or access policies
AuditCloudTrailCloudTrailCloud Audit LogsAzure Monitor diagnostic logs
Cost modelPer secret per month plus API callsStandard tier has no per-parameter charge (verify)Per active version plus access operationsPer operation; premium tier for HSM
Cross-regionReplication supportedManualReplication policy per secretGeo-redundancy by region pairs

Pricing changes; check each provider's current pricing page.

AWS Secrets Manager

# Create
aws secretsmanager create-secret \
  --name prod/api/stripe \
  --secret-string '{"api_key":"REPLACE_ME"}' \
  --kms-key-id alias/prod-secrets

# Read (never echo to logs in real automation)
aws secretsmanager get-secret-value --secret-id prod/api/stripe --query SecretString --output text

Least-privilege policy for one application role, restricted to its own prefix:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ReadOwnSecrets",
      "Effect": "Allow",
      "Action": ["secretsmanager:GetSecretValue", "secretsmanager:DescribeSecret"],
      "Resource": "arn:aws:secretsmanager:eu-west-1:111122223333:secret:prod/api/*"
    },
    {
      "Sid": "DecryptWithAppKey",
      "Effect": "Allow",
      "Action": "kms:Decrypt",
      "Resource": "arn:aws:kms:eu-west-1:111122223333:key/REPLACE-KEY-ID",
      "Condition": {
        "StringEquals": { "kms:ViaService": "secretsmanager.eu-west-1.amazonaws.com" }
      }
    }
  ]
}

Fetching from TypeScript with the AWS SDK v3, with a short in-memory cache:

import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";

const client = new SecretsManagerClient({}); // credentials come from the role, never from code
const cache = new Map<string, { value: string; fetchedAt: number }>();
const TTL_MS = 5 * 60 * 1000;

export async function getSecret(id: string): Promise<string> {
  const hit = cache.get(id);
  if (hit && Date.now() - hit.fetchedAt < TTL_MS) return hit.value;
  const res = await client.send(new GetSecretValueCommand({ SecretId: id }));
  if (!res.SecretString) throw new Error(`secret ${id} has no string value`);
  cache.set(id, { value: res.SecretString, fetchedAt: Date.now() });
  return res.SecretString;
}

Parameter Store is a cheaper option for configuration and low-rate secrets (SecureString), but lacks built-in rotation. A common split: Parameter Store for configuration, Secrets Manager for credentials that need rotation.

GCP Secret Manager

gcloud secrets create stripe-api-key --replication-policy=automatic
printf '%s' "$VALUE" | gcloud secrets versions add stripe-api-key --data-file=-

gcloud secrets add-iam-policy-binding stripe-api-key \
  --member="serviceAccount:api@my-project.iam.gserviceaccount.com" \
  --role="roles/secretmanager.secretAccessor"
from google.cloud import secretmanager

client = secretmanager.SecretManagerServiceClient()  # Application Default Credentials; no key file

def get_secret(project: str, name: str, version: str = "latest") -> str:
    path = f"projects/{project}/secrets/{name}/versions/{version}"
    return client.access_secret_version(request={"name": path}).payload.data.decode("utf-8")

Prefer pinning a version number or alias in production rather than latest, so a bad rotation does not instantly break every consumer, and promote deliberately.

Azure Key Vault

az keyvault create --name kv-prod-myapp --resource-group rg-prod --enable-rbac-authorization true
az keyvault secret set --vault-name kv-prod-myapp --name stripe-api-key --value "REPLACE_ME"

# Grant read to a managed identity with RBAC (least privilege role)
az role assignment create \
  --assignee-object-id "$PRINCIPAL_ID" --assignee-principal-type ServicePrincipal \
  --role "Key Vault Secrets User" \
  --scope "$(az keyvault show --name kv-prod-myapp --query id -o tsv)"
import { DefaultAzureCredential } from "@azure/identity";
import { SecretClient } from "@azure/keyvault-secrets";

const client = new SecretClient("https://kv-prod-myapp.vault.azure.net", new DefaultAzureCredential());
export async function getSecret(name: string) {
  const s = await client.getSecret(name);
  return s.value!;
}

Enable soft delete and purge protection on vaults holding anything you cannot afford to lose.

What the managers do not do

They store and authorize. They do not remove the need for: network restrictions (private endpoints, VPC endpoints), tight IAM, separating dev and prod accounts or projects, rotation automation for each third-party credential, and monitoring access. A secret manager with secretsmanager:* granted to every role is a very expensive .env file.

HashiCorp Vault and OpenBao

Vault is the reference implementation of a secrets platform. OpenBao is the community fork, hosted under the Linux Foundation, that continued from the last open source Vault release after HashiCorp changed Vault's license in 2023. For core concepts and API they are close cousins; for details such as features, versions and plugin compatibility, verify against each project's current docs. The concepts below apply to both, and vault and bao CLIs use the same shapes.

Why use it over a cloud manager

CapabilityValue
Dynamic secretsGenerate database, cloud and SSH credentials on demand with a TTL and automatic revocation
LeasesEvery dynamic secret has a lease; revoke a lease or a whole path in one command
Multi-cloud, on-premOne API and policy language everywhere
PKIRun an internal certificate authority, issue short-lived certificates
TransitEncryption as a service: apps send plaintext, get ciphertext, never see keys
Auth methodsKubernetes, JWT/OIDC, AppRole, AWS/GCP/Azure identity, LDAP, and more
Fine-grained policyPath-based policies, response wrapping, control groups (edition dependent)

The cost is operations. Vault is a stateful, security-critical system: unsealing, HA with integrated Raft storage, backups, upgrades, audit device management, and disaster recovery. If you are single-cloud and do not need dynamic secrets or PKI, a cloud manager is usually cheaper in total cost. If you want Vault without running it, look at hosted offerings and verify their current terms.

Architecture

 App pod / CI job
      |  1. authenticate with platform identity (K8s SA JWT, OIDC token, cloud IAM)
      v
 +-----------------------+        +-----------------------------+
 |  Vault / OpenBao      | -----> | Secrets engines             |
 |  auth methods         |        |  kv, database, pki, transit |
 |  policies (ACL)       | <----- |  aws, gcp, azure, ssh       |
 |  audit devices        |        +-----------------------------+
 +-----------------------+
      |  2. returns a short-lived token bound to policies
      |  3. app requests secret -> gets value + lease
      v
 Backends: PostgreSQL / MySQL / cloud APIs (creates a temporary user or credential)

Dynamic database credentials

vault secrets enable database

vault write database/config/appdb \
  plugin_name=postgresql-database-plugin \
  allowed_roles="app-readwrite" \
  connection_url="postgresql://{{username}}:{{password}}@db.internal:5432/app?sslmode=verify-full" \
  username="vault_admin" password="REPLACE_ME"

vault write database/roles/app-readwrite \
  db_name=appdb \
  creation_statements="CREATE ROLE \"{{name}}\" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}'; GRANT app_rw TO \"{{name}}\";" \
  default_ttl="1h" max_ttl="24h"

# Each read returns a brand-new username and password with a 1h lease
vault read database/creds/app-readwrite

After rotating the root credential (vault write -f database/rotate-root/appdb), even the administrator password is known only to Vault. The creation statements above use Vault's templating tokens; the double braces are Vault syntax, shown inside code fences only.

Policy

# policy: app-readwrite-policy
path "database/creds/app-readwrite" {
  capabilities = ["read"]
}

path "kv/data/prod/api/*" {
  capabilities = ["read"]
}

# Explicitly nothing else. Vault is deny-by-default.
vault policy write app-readwrite-policy app-readwrite-policy.hcl

Kubernetes authentication

The pod presents its service account token; Vault verifies it through the Kubernetes TokenReview API and maps the service account and namespace to a role and policies.

vault auth enable kubernetes

vault write auth/kubernetes/config \
  kubernetes_host="https://kubernetes.default.svc" \
  kubernetes_ca_cert=@/var/run/secrets/kubernetes.io/serviceaccount/ca.crt

vault write auth/kubernetes/role/api \
  bound_service_account_names=api \
  bound_service_account_namespaces=prod \
  policies=app-readwrite-policy \
  ttl=15m

Role bindings should name an exact service account and namespace. Wildcards (*) turn a namespace into a trust boundary you do not control.

Delivery options for the app:

PatternHow it worksTrade-off
Vault Agent sidecar or injectorMutating webhook adds an agent container that authenticates, renders secrets to a shared in-memory volume, renews leasesExtra container per pod; app reads files; supports templates and re-render on change
Vault Secrets Operator (VSO)Operator syncs to Kubernetes Secrets or dynamic secrets, handles renewal and rolloutSecrets land in Kubernetes Secret objects (and etcd)
CSI providerMounts secrets as volumes through the Secrets Store CSI DriverNeeds the driver; optional sync to Kubernetes Secrets
App uses the API or SDK directlyApp authenticates and fetches itselfMost control, most code; good for dynamic credentials with in-process pooling
External Secrets OperatorSync from Vault KV into Kubernetes SecretsConvenient and uniform with other backends; dynamic secrets support is limited, so verify

OpenBao ships equivalents of the injector and agent; some operator and CSI integrations are named differently or live in separate projects, so check the OpenBao docs for your delivery option.

Operating notes

  • Unseal: use cloud KMS auto-unseal (or a transit seal from another Vault) rather than manual key shares in production.
  • Audit devices: enable at least two (file and syslog or socket). Vault blocks requests if no audit device can record them, by design.
  • Do not use the root token after bootstrap; revoke it and use policy-limited identities.
  • Backups: snapshot the Raft storage regularly and test restore.
  • Namespaces (an enterprise Vault feature; OpenBao has its own namespace support, verify the current status) isolate teams.
  • Upgrade cadence: security releases matter; subscribe to advisories.

Common mistakes

  • A wildcard policy such as path "secret/*" { capabilities = ["read", "list"] } for every app.
  • Long default TTLs that defeat the point of dynamic secrets.
  • Apps that fetch dynamic credentials once at start and never renew them (connection failures after the TTL).
  • Using static root tokens in CI.
  • Forgetting that Kubernetes auth trusts whoever can create pods using a given service account.

SOPS with age, and the External Secrets Operator

Two tools cover the "GitOps and Kubernetes" case from opposite directions. SOPS encrypts values inside files so ciphertext lives in Git. External Secrets Operator (ESO) keeps secrets out of Git entirely and syncs them from a manager into the cluster.

SOPS with age

SOPS (originally from Mozilla, now a CNCF project) encrypts the values of YAML, JSON, ENV and INI files while leaving keys readable, so diffs still make sense. It supports age, PGP, and cloud KMS backends (AWS KMS, GCP KMS, Azure Key Vault) and HashiCorp Vault transit. age is a small, modern file encryption tool; it is generally preferred over PGP for new setups.

# One-time: create an age key pair (store the private key in a password manager or secret manager)
age-keygen -o ~/.config/sops/age/keys.txt
# Public key: age1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs3290gq  (example format)
# .sops.yaml  (repository root)
creation_rules:
  - path_regex: ^environments/prod/.*\.enc\.ya?ml$
    encrypted_regex: ^(data|stringData)$      # Kubernetes Secret manifests
    age: age1PROD_PUBLIC_KEY_HERE,age1CI_PUBLIC_KEY_HERE
  - path_regex: ^environments/dev/.*\.enc\.ya?ml$
    age: age1DEV_PUBLIC_KEY_HERE
sops --encrypt --in-place environments/prod/db-secret.enc.yaml
sops environments/prod/db-secret.enc.yaml           # opens $EDITOR with decrypted view; saves encrypted
sops --decrypt environments/prod/db-secret.enc.yaml | kubectl apply -f -

Key points:

  1. Multiple recipients: each developer, the CI system and the cluster controller get their own key. Removing a person means removing their recipient and re-encrypting (sops updatekeys), then rotating the secrets they could read.
  2. Environment separation: separate keys per environment so a developer with dev access cannot decrypt prod.
  3. Cloud KMS backend gives audit logs and IAM control over who can decrypt; age keys are files and have no built-in audit.
  4. Keep the private key out of the repository. The classic mistake is committing keys.txt next to the encrypted files.
  5. Enforce encryption in CI: fail a commit that adds a plaintext file matching *.enc.yaml. A simple check is that every such file contains a top-level sops: key.
# pre-commit or CI guard: every *.enc.* file must carry SOPS metadata
for f in $(git ls-files '*.enc.yaml' '*.enc.yml' '*.enc.json'); do
  grep -q '^sops:' "$f" || grep -q '"sops":' "$f" || { echo "NOT ENCRYPTED: $f"; exit 1; }
done

Flux has native SOPS decryption in the Kustomize controller:

# Flux Kustomization with SOPS decryption
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: apps-prod
  namespace: flux-system
spec:
  interval: 10m
  path: ./environments/prod
  prune: true
  sourceRef:
    kind: GitRepository
    name: platform
  decryption:
    provider: sops
    secretRef:
      name: sops-age        # Secret containing the age private key (bootstrap manually)

Argo CD does not decrypt SOPS natively; common patterns use a plugin or KSOPS, or use ESO instead. Verify the current recommended integration in the Argo CD docs.

SOPS limits: secrets are still ultimately a file with a key; rotation means re-encrypting and committing; the Git history keeps old ciphertext (so rotate the data key and the secrets if a key leaks). There is no runtime access control or audit beyond what KMS gives you.

External Secrets Operator

ESO runs in the cluster and reconciles ExternalSecret resources into Kubernetes Secrets, reading from AWS Secrets Manager and Parameter Store, GCP Secret Manager, Azure Key Vault, Vault and OpenBao, 1Password, and many others. Git contains only references, never values. The API group and version have changed across ESO releases; verify the current apiVersion against the project docs.

# 1. Tell ESO how to authenticate to the backend (here: AWS via IRSA / pod identity on the controller)
apiVersion: external-secrets.io/v1
kind: ClusterSecretStore
metadata:
  name: aws-secrets
spec:
  provider:
    aws:
      service: SecretsManager
      region: eu-west-1
      auth:
        jwt:
          serviceAccountRef:
            name: external-secrets
            namespace: external-secrets
---
# 2. Declare what to sync
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata:
  name: api-secrets
  namespace: prod
spec:
  refreshInterval: 10m
  secretStoreRef:
    kind: ClusterSecretStore
    name: aws-secrets
  target:
    name: api-secrets
    creationPolicy: Owner
  data:
    - secretKey: STRIPE_API_KEY
      remoteRef:
        key: prod/api/stripe
        property: api_key
    - secretKey: DATABASE_URL
      remoteRef:
        key: prod/api/database
        property: url

Design notes:

  • refreshInterval governs how fast rotation propagates to the Kubernetes Secret. Pods need to re-read it (volume mounts update; env vars do not) or be restarted by a tool like Reloader.
  • Namespace-scoped SecretStore over ClusterSecretStore when tenants should not be able to read each other's secrets; a ClusterSecretStore can be used from any namespace unless you restrict it with conditions.
  • ESO is a sync tool: the value still ends up in a Kubernetes Secret, so enable encryption at rest for etcd (with a KMS provider), restrict RBAC on secrets, and keep get/list on Secrets off developer roles.
  • For no-Secret-object delivery, use the Secrets Store CSI Driver or Vault Agent.

Decision table

NeedSOPS + age/KMSESOSealed SecretsVault Agent / CSI
Secrets in Git (encrypted)YesNo (references only)Yes (cluster-key encrypted)No
Central rotation, auditLimited (KMS)Yes (from backend)NoYes
Works outside KubernetesYesNoNoPartly
Operational burdenLowMedium (operator)Low (controller)Medium to high
Dynamic secretsNoLimitedNoYes (Vault)
Good forSmall teams, GitOps, bootstrap secretsMulti-service clusters with a cloud managerSimple GitOps, single clusterStrict, regulated, dynamic credentials

A pragmatic combination: SOPS for bootstrap secrets (the ESO credentials, the Flux age key, anything needed before the manager is reachable) and ESO for everything else.

Workload identity and OIDC federation: no static keys

The best secret is the one that does not exist. Workload identity replaces "here is a key file" with "I am workload X, here is a short-lived signed token from an issuer you trust; exchange it for temporary cloud credentials".

  GitHub Actions job                 Cloud identity provider                  Cloud API
  -------------------                -----------------------                  ---------
  1. request OIDC token  ----------> GitHub OIDC issuer signs JWT
     (id-token: write)               claims: repo, ref, environment, workflow
  2. present JWT  -----------------> STS / token exchange verifies signature,
                                     issuer, audience, and trust-policy conditions
  3. <----------------------------- short-lived access token (minutes to 1 hour)
  4. call API with temporary token ---------------------------------------->  authorized by role

The trust policy is the security boundary. A policy that trusts "any token from GitHub" is a vulnerability: any repository on GitHub could assume your role. Always restrict by repository, and ideally by branch, environment, or workflow ref.

GitHub Actions to AWS

# Terraform: OIDC provider and a role only your repo's main branch (and prod environment) can assume
resource "aws_iam_openid_connect_provider" "github" {
  url            = "https://token.actions.githubusercontent.com"
  client_id_list = ["sts.amazonaws.com"]
  # AWS validates GitHub's certificate chain; thumbprint requirements have changed, verify current docs
  thumbprint_list = ["6938fd4d98bab03faadb97b34396831e3780aea1"]
}

data "aws_iam_policy_document" "trust" {
  statement {
    actions = ["sts:AssumeRoleWithWebIdentity"]
    principals {
      type        = "Federated"
      identifiers = [aws_iam_openid_connect_provider.github.arn]
    }
    condition {
      test     = "StringEquals"
      variable = "token.actions.githubusercontent.com:aud"
      values   = ["sts.amazonaws.com"]
    }
    condition {
      test     = "StringEquals"
      variable = "token.actions.githubusercontent.com:sub"
      values   = ["repo:my-org/my-repo:environment:production"]
    }
  }
}

resource "aws_iam_role" "deploy" {
  name               = "gha-deploy-prod"
  assume_role_policy = data.aws_iam_policy_document.trust.json
  max_session_duration = 3600
}
# .github/workflows/deploy.yml
name: deploy
on:
  push:
    branches: [main]

permissions:
  id-token: write     # required to request the OIDC token
  contents: read

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production        # environment protection rules + the sub claim above
    steps:
      - uses: actions/checkout@v4
        with: { persist-credentials: false }
      - uses: aws-actions/configure-aws-credentials@v4   # verify the current major version; pin by SHA
        with:
          role-to-assume: arn:aws:iam::111122223333:role/gha-deploy-prod
          aws-region: eu-west-1
      - run: aws sts get-caller-identity
      - run: ./scripts/deploy.sh

The sub claim format depends on the trigger: repo:ORG/REPO:ref:refs/heads/main for branch runs, repo:ORG/REPO:environment:NAME when a job uses an environment, repo:ORG/REPO:pull_request for PRs. GitHub also supports customizing the subject claim template per organization or repository; check the current docs for the exact claim names.

GitHub Actions to GCP

gcloud iam workload-identity-pools create github --location=global --display-name="GitHub"

gcloud iam workload-identity-pools providers create-oidc github-oidc \
  --location=global --workload-identity-pool=github \
  --issuer-uri="https://token.actions.githubusercontent.com" \
  --attribute-mapping="google.subject=assertion.sub,attribute.repository=assertion.repository,attribute.ref=assertion.ref" \
  --attribute-condition="assertion.repository=='my-org/my-repo' && assertion.ref=='refs/heads/main'"

gcloud iam service-accounts add-iam-policy-binding deploy@my-project.iam.gserviceaccount.com \
  --role="roles/iam.workloadIdentityUser" \
  --member="principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/github/attribute.repository/my-org/my-repo"
      - uses: google-github-actions/auth@v2       # verify current major version
        with:
          workload_identity_provider: projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/github/providers/github-oidc
          service_account: deploy@my-project.iam.gserviceaccount.com
      - uses: google-github-actions/setup-gcloud@v2
      - run: gcloud run deploy api --image "$IMAGE" --region europe-west1

GCP requires an attribute condition on providers for external identities in current configurations; verify the exact requirement in the docs.

GitHub Actions to Azure

# Create an app registration and a federated credential (no client secret)
az ad app create --display-name gha-deploy
APP_ID=$(az ad app list --display-name gha-deploy --query "[0].appId" -o tsv)
az ad sp create --id "$APP_ID"

az ad app federated-credential create --id "$APP_ID" --parameters '{
  "name": "gha-prod",
  "issuer": "https://token.actions.githubusercontent.com",
  "subject": "repo:my-org/my-repo:environment:production",
  "audiences": ["api://AzureADTokenExchange"]
}'
      - uses: azure/login@v2         # verify current major version
        with:
          client-id: ${{ secrets.AZURE_CLIENT_ID }}       # identifiers, not secrets; vars also fine
          tenant-id: ${{ secrets.AZURE_TENANT_ID }}
          subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}

Client, tenant and subscription IDs are identifiers, not secrets. Storing them as repository variables is fine and avoids confusion.

Kubernetes workloads to cloud APIs

PlatformMechanismHow it works
AWS EKSIRSA (IAM Roles for Service Accounts) or EKS Pod IdentityProjected service account token exchanged for role credentials; Pod Identity uses an agent and simpler association API
GCP GKEWorkload Identity Federation for GKEKubernetes service accounts map to IAM principals directly or via impersonated Google service accounts
Azure AKSMicrosoft Entra Workload IDProjected token federated with a managed identity or app registration
Any clusterSPIFFE/SPIREIssues workload identities (SVIDs) usable for mTLS and OIDC-style federation
# EKS IRSA: annotate the service account (Pod Identity uses an association instead)
apiVersion: v1
kind: ServiceAccount
metadata:
  name: api
  namespace: prod
  annotations:
    eks.amazonaws.com/role-arn: arn:aws:iam::111122223333:role/prod-api
automountServiceAccountToken: true
# GKE: grant the Kubernetes service account direct access to a secret (no key file anywhere)
# roles/secretmanager.secretAccessor bound to the principal:
# principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/PROJECT_ID.svc.id.goog/subject/ns/prod/sa/api

Pod-level rules: one service account per workload; do not share the namespace's default account; disable automounting tokens for pods that do not need them; make sure the IMDS (instance metadata) path cannot be used by pods to obtain the node's broader credentials (IMDSv2 with hop limit 1, or network policy).

Publishing packages without long-lived tokens

npm and PyPI both support trusted publishing via OIDC, so a release workflow gets a short-lived credential tied to a repository and workflow rather than a stored publish token. Enable it where available and remove the old tokens. Verify the setup steps against the current npm and PyPI docs, since the UI and requirements are evolving.

Common mistakes with OIDC federation

  • Trust policy matches only the issuer, not the sub, repository, or ref.
  • Wildcard subjects such as repo:my-org/*.
  • Allowing pull_request triggers from forks to assume deploy roles.
  • Forgetting permissions: id-token: write, then falling back to static keys "just to get it working".
  • Overly broad role permissions: the identity is keyless but the role is AdministratorAccess.
  • Keeping the old access keys after the migration. Delete them.

Migration checklist: static keys to OIDC

  1. Inventory every static cloud key (IAM access keys, service account JSON files, client secrets) using the cloud's credential report.
  2. Create the OIDC provider and one role per pipeline, scoped to the minimum actions.
  3. Update the workflow; run it in a non-production account first.
  4. Compare the actions in CloudTrail or audit logs to confirm the new role is used.
  5. Deactivate the old key, wait a week, delete it, and remove the CI secret.

Application patterns: fetch at start, sidecar, env injection

How the secret reaches the process matters as much as where it is stored.

PatternFlowProsConsUse when
Platform env injectionPlatform (ECS, Cloud Run, App Service, Kubernetes) injects secret refs as env vars at startSimple; no SDK; works for any languageNeeds restart to rotate; visible in process env and some consolesStatic secrets, 12-factor style apps
Mounted file (tmpfs or CSI)Secret appears at a path; app reads the fileUpdates without restart if app re-reads; permissions; no env leakApp must handle reloadCertificates, config, rotating secrets
Fetch at startup via SDKApp authenticates and pulls secrets onceMinimal infrastructure; fine-grainedRotation requires restart; startup depends on the managerSmall services
Fetch with refreshApp caches and refreshes on TTL or on auth failureRotation without redeployMore code; cache invalidation logicRotating API keys and DB passwords
Sidecar or agentAgent authenticates, renders, renews, re-templatesApp stays simple; supports dynamic secretsExtra container; more moving partsVault dynamic secrets, legacy apps
Transit / encryption serviceApp never holds the key; calls an API to encrypt or signKey never leaves the vaultLatency; availability dependencyField encryption, signing
Proxy injectionEgress proxy adds the API key to outbound requestsApp never sees the key at allNeeds a proxy and policyAI agents, third-party API calls

An in-app pattern that holds up: lazy fetch with refresh on failure

// secrets.ts: central access point; nothing else in the codebase reads process.env for secrets
type Loader = () => Promise<string>;

class Secret {
  private value?: string;
  private fetchedAt = 0;
  constructor(private load: Loader, private ttlMs = 5 * 60_000) {}

  async get(): Promise<string> {
    if (!this.value || Date.now() - this.fetchedAt > this.ttlMs) await this.refresh();
    return this.value!;
  }

  async refresh(): Promise<void> {
    this.value = await this.load();
    this.fetchedAt = Date.now();
  }
}

export const stripeKey = new Secret(() => getSecret("prod/api/stripe"));

// Caller pattern: on 401, refresh once and retry (handles rotation mid-flight)
export async function callStripe(path: string, init: RequestInit = {}) {
  for (let attempt = 0; attempt < 2; attempt++) {
    const key = await stripeKey.get();
    const res = await fetch(`https://api.stripe.com${path}`, {
      ...init,
      headers: { ...init.headers, Authorization: `Bearer ${key}` },
    });
    if (res.status !== 401 || attempt === 1) return res;
    await stripeKey.refresh();
  }
  throw new Error("unreachable");
}
# Python: same idea with functools-style TTL cache
import time, threading

class RefreshingSecret:
    def __init__(self, loader, ttl=300):
        self._loader, self._ttl = loader, ttl
        self._value, self._at, self._lock = None, 0.0, threading.Lock()

    def get(self) -> str:
        with self._lock:
            if self._value is None or time.time() - self._at > self._ttl:
                self._value, self._at = self._loader(), time.time()
            return self._value

    def invalidate(self):
        with self._lock:
            self._value = None

Hygiene inside the process

  • Wrap secrets in a type that refuses to print. A class whose toString and JSON serialization return [REDACTED] prevents the accidental console.log(config).
  • Redact at the logger (pino redact, structlog processors) for headers and known keys.
  • Never put secrets in command-line arguments (visible in ps and shell history) or URLs (logged by proxies).
  • Fail fast with a clear error (without the value) when a required secret is missing at startup.
  • Disable core dumps and debug endpoints in production.
export class Redacted<T extends string> {
  constructor(private readonly value: T) {}
  reveal(): T { return this.value; }
  toString() { return "[REDACTED]"; }
  toJSON() { return "[REDACTED]"; }
  [Symbol.for("nodejs.util.inspect.custom")]() { return "[REDACTED]"; }
}

Docker and Compose secrets

# compose.yaml: file-based secrets mounted at /run/secrets/NAME
services:
  api:
    image: ghcr.io/my-org/api:1.4.2
    secrets:
      - db_password
    environment:
      DB_PASSWORD_FILE: /run/secrets/db_password

secrets:
  db_password:
    file: ./secrets/db_password.txt   # git-ignored; or use `environment:` / external sources

Many official images (PostgreSQL, MySQL) support the _FILE convention. Read the file in your own app the same way.

Systemd on a VPS

# /etc/systemd/system/api.service
[Service]
ExecStart=/usr/local/bin/api
LoadCredential=db_password:/etc/api/secrets/db_password
# App reads $CREDENTIALS_DIRECTORY/db_password; file is private to the service
DynamicUser=yes
NoNewPrivileges=yes
ProtectSystem=strict

Rotation without downtime

Rotation is the control that turns a leak from a catastrophe into a non-event, but only if it is routine. Unrehearsed rotation breaks production.

The dual-credential pattern

Phase 1  Create new credential B alongside A.        (A active, B active)
Phase 2  Deploy/refresh consumers so they use B.      (verify via metrics/logs)
Phase 3  Confirm nothing uses A (audit logs, 0 reads).
Phase 4  Disable A, wait a safe period.
Phase 5  Delete A.

The system must accept two valid credentials at once during the window. How to get that:

Secret typeDual-valid mechanism
Database passwordTwo database roles (alternating "blue" and "green" users), or Vault dynamic credentials where every client has its own
API keys at a providerProviders with multiple active keys; create the new key, deploy, revoke the old
JWT signing keysPublish a JWKS with multiple keys; sign with the new kid, keep verifying with the old until tokens expire
Webhook signing secretsVerify against a list of secrets for a grace period
TLS certificatesAutomated renewal (ACME) with overlapping validity
Encryption keysEnvelope encryption: rotate the key-encryption key, re-wrap data keys lazily; keep old key versions for decryption
Session or cookie secretsAccept an array of secrets: sign with the first, verify with all
// Verifying with an overlapping list of webhook secrets
import crypto from "node:crypto";

export function verifyAny(raw: Buffer, signature: string, secrets: string[]): boolean {
  return secrets.some((s) => {
    const expected = crypto.createHmac("sha256", s).update(raw).digest("hex");
    return expected.length === signature.length &&
      crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
  });
}

AWS Secrets Manager rotation labels

Secrets Manager uses staging labels: AWSCURRENT (in use), AWSPENDING (new, being tested), AWSPREVIOUS (prior version). A rotation function runs four steps: create, set, test, finish. The "alternating users" strategy keeps one valid user while updating the other. Use the managed rotation templates for supported databases rather than writing your own Lambda where possible; verify the current list of supported services.

Making applications rotation-friendly

  1. Reload on change: re-read mounted files (file watcher or periodic), or refresh on 401 as in the in-app pattern earlier.
  2. Connection pools: when a DB password changes, existing connections remain valid, but new connections must use the new one. Recycle pools gradually.
  3. Short-lived credentials by design: Vault dynamic secrets or IAM database authentication (RDS and Cloud SQL IAM auth give 15-minute tokens as passwords) eliminate rotation as a task.
  4. Restart as a rotation strategy is acceptable if rolling restarts are safe. A Reloader annotation or a rollout triggered from the secret change works well.
  5. Rotation observability: emit a metric or log (without the value) when a secret version changes, and alert when a secret exceeds its maximum age.
# Kubernetes: restart pods when a referenced Secret changes (Stakater Reloader annotation)
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
  annotations:
    secret.reloader.stakater.com/reload: "api-secrets"

Rotation schedule guidance

SecretSuggested approach
Cloud credentialsEliminate static ones; if unavoidable, 90 days or less with automation
Database passwordsDynamic credentials, or 30 to 90 days with automation
Third-party API keysOn personnel change, on suspected leak, and at least yearly; more often if the provider supports automation
Signing keys (JWT, webhook)On a schedule (for example 90 to 180 days) with overlap
TLS certificatesAutomated; lifetimes are getting shorter industry-wide, verify current CA/B Forum rules
Human passwordsPer current NIST guidance, change on evidence of compromise, not on a fixed calendar

These intervals are starting points, not mandates. Choose what you can automate and verify, and what your compliance regime requires.

Local development

Developers need working credentials without production exposure.

PracticeWhy
Use dev-only secrets for dev services; never copy production values to laptopsA lost laptop must not equal a production breach
Pull secrets at run time from a manager CLINo long-lived file on disk
Use per-developer credentials where the provider allowsAttribution and individual revocation
Use local emulators (LocalStack, Stripe CLI test mode, fake SMTP)Fewer real secrets needed at all
Use a dev container or compose stack with fake values committed as .env.exampleNew hire runs the app without asking for secrets
Authenticate to the cloud using SSO and short-lived sessionsaws sso login, gcloud auth login, az login instead of access keys
# Run a command with secrets injected from a manager without writing a file.
# Examples (choose the tool you actually use; verify syntax in each tool's docs):
op run --env-file=.env.tpl -- npm run dev        # 1Password CLI: .env.tpl holds op:// references
doppler run -- npm run dev                        # Doppler
sops exec-env secrets.dev.enc.env 'npm run dev'   # SOPS: decrypt into the child's environment only
# .env.example (committed): shape and safe defaults only
DATABASE_URL=postgresql://app:app@localhost:5432/app_dev
STRIPE_API_KEY=sk_test_REPLACE_WITH_YOUR_OWN_TEST_KEY
SESSION_SECRET=generate-with-openssl-rand-base64-32
# Generate strong local secrets
openssl rand -base64 32

Also: add .env, .env.* (except .env.example), *.pem, *.key, *.tfstate* to .gitignore and .dockerignore; install the pre-commit scanner in the repository's setup script so it is not optional; and never paste secrets into issue trackers or chats. Use a one-time-secret sharing link or the manager's sharing feature when a human-to-human handoff is unavoidable.

Audit, least privilege and ownership

A secret manager with weak policy and no logs gives false comfort.

Least privilege

  • One identity per workload, one role per purpose. Do not reuse the CI role for runtime.
  • Path or prefix scoping: prod/api/* for the API, not *.
  • Separate environments in separate accounts, projects or vaults. A staging bug should not read production secrets.
  • Deny by default; add explicit permissions and review them.
  • Separate read from manage: apps get GetSecretValue; only a small admin group or automation can PutSecretValue, delete or change policies.
  • Break-glass access with approvals, time limits and alerts.
  • Condition keys (source VPC endpoint, IP, MFA, tag-based access control) add depth.

Audit and alerting

SignalWhy it matters
Reads of a secret from an unexpected principal or IPPossible theft or misconfigured access
Read spikeScraping or a loop bug
Policy changes on secrets or keysPrivilege escalation prep
Secret deletion or scheduled key deletionSabotage or a mistake
Failed access attemptsProbing
Secret age over maximumRotation drift
Disabling of audit logsAnti-forensics

Send audit logs (CloudTrail, Cloud Audit Logs, Azure diagnostics, Vault audit devices) to a separate, write-restricted logging account. Create alerts for the first four rows, and a weekly report for the last two.

Inventory and ownership

Maintain a registry (a table in your secret manager's tags, a catalog in the developer portal, or a YAML file in the platform repo):

# secrets-inventory.yaml (no values, only metadata)
- name: prod/api/stripe
  owner: payments-team
  purpose: Server-side Stripe API calls
  consumers: [api, billing-worker]
  rotation: manual-quarterly   # provider supports rolling keys
  last_rotated: 2026-09-14
  data_class: high
  runbook: https://wiki.example.com/runbooks/rotate-stripe

Tag secrets in the manager with owner, environment, rotation, data_class, and use tag-based IAM conditions and cost reports. Every secret must answer: who owns it, what is it for, who uses it, when does it expire, how do I rotate it.

Secrets for AI agents and MCP servers

AI coding agents, chat assistants with tools, and MCP servers are a fast-growing class of secret consumers, with extra risks because a language model can be manipulated by content it reads (see Prompt Injection Defense for AI Agents). The threat model: an injected instruction convinces the agent to read a secret and send it somewhere, or to print it into a log, a pull request or a chat.

Principles

  1. The model should never see the raw secret. Prompts, tool arguments, tool results and conversation logs are all places secrets get retained and leaked. Let the tool runtime or a proxy attach credentials after the model decides to call a tool.
  2. Least privilege per tool. An agent that reads issues needs a read-only, repository-scoped token, not a personal token with full account access.
  3. Short-lived, task-scoped credentials. Mint a token for the task (GitHub app installation tokens expire in an hour; cloud STS tokens expire in minutes) and let it die.
  4. Separate the agent's identity from the human's. Give agents their own service accounts so actions are attributable and revocable.
  5. Block exfiltration paths. Egress allow-lists for agent sandboxes; no ambient credentials in the environment; deny reading ~/.aws, ~/.ssh, .env, and token stores.
  6. Human approval for high-impact actions such as publishing packages, rotating production secrets, or deploying.
  7. Scan agent output. Run secret scanning on agent-authored commits and pull requests, and redact secrets in transcripts.

Patterns for MCP servers

ConcernRecommendation
Where the server's credentials liveIn the server process environment or its secret manager, never in the client config checked into a repository, and never in the tool schema or prompts
Remote MCP serversUse OAuth 2.1 flows as defined by the MCP authorization specification (verify the current spec revision) with scoped, expiring tokens, rather than static API keys shared among users
Per-user accessDelegate with the user's own authorization (token exchange or on-behalf-of) so the server cannot do more than the user can
Tool designTools like get_secret(name) returning values to the model are an anti-pattern. Prefer tools that perform the action (for example deploy(service)) with credentials the model never sees
Config filesKeep .mcp.json and agent settings free of tokens; reference environment variables that the launcher injects from a manager
Third-party serversTreat them as untrusted code with access to whatever credentials you give them; run in a container with limited egress; pin versions
// .mcp.json (committed): references only, no values
{
  "mcpServers": {
    "github": {
      "command": "node",
      "args": ["./tools/github-mcp/index.js"],
      "env": {
        // The launcher resolves this from a secret manager at start; the file holds no token
        "GITHUB_TOKEN": "${GITHUB_TOKEN}"
      }
    }
  }
}

The exact configuration format and variable expansion support differ between clients; verify against your client's current documentation.

A credential-injecting proxy for agents

For model-driven HTTP calls, run an egress proxy in front of the agent sandbox that adds the Authorization header for allow-listed hosts and drops everything else. The model asks for "call the billing API"; the proxy supplies the credential. A compromised or manipulated model can misuse the allowed actions, but cannot exfiltrate the key or reach other hosts.

 Agent sandbox (no secrets, no direct internet)
        |  HTTP request to api.billing.example.com  (no auth header)
        v
 Egress proxy ---- policy: allow host, allow methods, rate limit, log
        |  injects Authorization from secret manager (short-lived token)
        v
 api.billing.example.com

Agent checklist

  • Agent runs with its own identity and the minimum scopes.
  • No secrets in prompts, rules files, memory stores, or chat logs.
  • Credentials injected outside the model's context; short-lived where possible.
  • Sandboxed filesystem excludes credential locations; network egress restricted.
  • Secret scanning on every agent-authored change.
  • High-impact actions require human confirmation.

A worked example: a small SaaS from .env to workload identity

Starting point: a Next.js and worker app on Kubernetes, with a Postgres database on AWS RDS, Stripe, and a GitHub Actions pipeline that deploys with a stored AWS_ACCESS_KEY_ID. Secrets live in a .env.production file copied to the servers.

Target state

GitHub Actions --OIDC--> AWS role (deploy only, environment: production)
Kubernetes pods --IRSA/Pod Identity--> AWS role (read prod/api/* secrets only)
External Secrets Operator --> syncs Stripe key + DB URL to Kubernetes Secrets
RDS --> IAM database authentication for the worker; password rotated by Secrets Manager for the app
Git repo --> SOPS-encrypted bootstrap secrets only; gitleaks + push protection

Step by step

  1. Stop the bleeding (day 1). Enable GitHub push protection and add gitleaks to CI. Scan history; rotate anything found. Add .env* to .gitignore and .dockerignore. Check images for baked-in secrets (trufflehog docker).
  2. Inventory (day 2). List every secret, its consumers and the owner using a spreadsheet or the YAML format from the inventory and ownership section. Delete unused ones.
  3. Move to a manager (week 1). Create entries in AWS Secrets Manager under prod/api/. Grant read to a new role for the app. Deploy ESO and an ExternalSecret. Switch the Deployment to read from the generated Kubernetes Secret.
  4. Pod identity (week 1). Bind the service account to the role; delete any AWS keys from the pod environment.
  5. OIDC for CI (week 2). Create the OIDC provider and deploy role, update the workflow, remove the AWS key from CI secrets, deactivate then delete the IAM user key.
  6. Rotation (week 3). Enable managed rotation for the DB secret using the alternating users strategy; make the app refresh pools. Add Reloader. Run a rotation game day.
  7. Audit (week 4). Enable CloudTrail data events for Secrets Manager reads, alert on reads from unknown principals, and set up secret age alerts.
  8. Etcd and RBAC. Enable KMS-backed encryption of Secrets at rest in the cluster; remove get secrets from developer roles.
  9. Document and rehearse the leak playbook from the rotation playbook section.

The resulting workflow, in short

# deployment fragment: no secret values anywhere in Git
spec:
  template:
    spec:
      serviceAccountName: api            # bound to an IAM role via IRSA / Pod Identity
      containers:
        - name: api
          image: ghcr.io/my-org/api@sha256:REPLACE_WITH_DIGEST
          envFrom:
            - secretRef:
                name: api-secrets        # created and refreshed by External Secrets Operator

Where this usually goes wrong

  1. One shared secret for everything. Blast radius is the sum of everything it unlocks.
  2. Secrets in Terraform state or Helm values committed to Git. State holds secret values in plaintext; encrypt the backend, restrict access, and use ephemeral or write-only attributes where your tooling supports them (verify).
  3. Trusting log masking. Secrets printed in transformed form are not masked.
  4. Base64 equals encrypted. It does not. Kubernetes Secrets are base64-encoded by default.
  5. Wildcard trust in OIDC conditions.
  6. No owner. The secret everyone depends on and nobody maintains.
  7. Rotation designed but never exercised. The first real rotation then becomes the outage.
  8. Moving secrets into a manager but granting everyone access to it.
  9. Keeping the old key "just in case". It is the one that leaks.
  10. Different treatment for non-production. Staging credentials that reach production data, or staging breaches that pivot into production.
  11. Using human credentials in automation. When the person leaves, builds break or, worse, nothing is revoked.
  12. Ignoring non-obvious secrets: Terraform state, kubeconfigs, container registry auth files (~/.docker/config.json), browser session cookies on build machines.

When not to do this (or when simpler is fine)

  • Do not run Vault or OpenBao for five secrets. The operational burden outweighs the benefit. A cloud manager or SOPS is enough until you need dynamic secrets, PKI, or multi-cloud.
  • Do not adopt ESO, CSI drivers, and Vault Agent together. Pick one delivery mechanism per platform.
  • Do not build your own secret manager or encryption scheme.
  • Do not rotate everything weekly if you cannot do it safely. A failed automated rotation causes outages and teaches people to disable rotation. Start with the credentials that matter most and can rotate safely, and automate gradually.
  • Do not put public or low-risk configuration through the secret manager. It adds latency, cost and friction without risk reduction.
  • Do not use SOPS as a runtime access control system. It protects storage, not usage.
  • Do not replace secrets with OIDC where the other side does not support federation. Third-party SaaS APIs often only offer static keys; store them well, scope them, and rotate manually on a schedule.
  • Hobby project on one server: an encrypted file with SOPS and age, a systemd credential or Docker secret, a secret scanning hook and a password manager is a respectable and sufficient setup.

Maturity roadmap

LevelDescriptionKey actions
0. Ad hocSecrets in code, .env everywhere, shared passwordsStop the bleeding: scanning, push protection, .gitignore, rotate exposed secrets
1. BaselineSecrets out of Git; a manager exists; CI scanningPick one secret manager; move production secrets; inventory and owners
2. FederatedNo static cloud keys in CI or workloadsOIDC for CI; workload identity for pods and serverless; delete old keys
3. Managed rotationAutomated rotation for the key credentials; apps handle rotationDual-credential patterns; reloaders; rotation game days
4. Dynamic and auditedShort-lived credentials, anomaly alerts, ownership enforcedVault/OpenBao or IAM database auth; audit alerts; secret age SLOs
5. Defense in depthTamper-resistant audit, break-glass, agent-safe credential injectionEgress proxies, per-task credentials, regular drills, policy as code

A sensible 90-day plan for a small team: weeks 1 to 2 on level 0 to 1 actions, weeks 3 to 8 on OIDC and workload identity, weeks 9 to 12 on rotation and audit. Measure progress with a few numbers: count of static long-lived cloud keys (target: zero), count of secrets without an owner (zero), median secret age, time to rotate a leaked credential in a drill, and scanner findings open longer than the SLA.

If you take only one action from all of this, list every static credential your CI and workloads use today and replace the cloud ones with federation this quarter. It removes your highest-value leak targets and teaches the team the pattern for everything else.

Questions that come up

Is it safe to commit encrypted secrets with SOPS to a public repository? It is as safe as your key management. Ciphertext stays in Git history forever, so any future key compromise exposes every past version. For public repositories, prefer references to an external manager. If you do commit ciphertext, use a KMS backend with audit logs and rotate the secrets (not just the key) when people leave.

Are Kubernetes Secrets secure? They are access-controlled objects stored base64-encoded in etcd, not encrypted by default. Enable encryption at rest (preferably with a KMS provider), restrict RBAC, avoid giving developers broad get secrets, and consider mounting from an external manager through CSI.

Do I still need secret scanning if I use a secret manager? Yes. Humans still paste secrets into code, configs, tickets, and chats. Scanning is the safety net, and push protection is the cheapest control with the most return.

How do I handle secrets in serverless and PaaS? Use the platform's native integrations: Lambda with Secrets Manager or Parameters extension, Cloud Run with Secret Manager references, Azure Functions and App Service with Key Vault references. All can resolve secrets at deploy or start using the platform's identity, so no credentials are in your config.

What do I do about secrets already in Git history? Rotate them, then decide whether rewriting history is worth it. Rewriting is helpful for hygiene and for reducing accidental rediscovery, but it never un-leaks a secret that was already public.

Is a .env file ever acceptable? For local development with non-production values, yes. For production, use platform injection from a manager.

Sources and docs