Production-grade guide to secrets rotation automation covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.
Secrets rotation automation is the practice of programmatically replacing long‑lived credentials—API keys, database passwords, TLS client secrets, service‑to‑service tokens—on a defined cycle without human intervention. It matters when you operate distributed services that authenticate to one another, when CI/CD pipelines provision transient credentials, or when compliance frameworks impose maximum secret lifetimes. The objective is to eliminate the “set‑and‑forget” state, reduce the window of exposure if a credential leaks, and avoid the operational burden of manual rotation across dozens or hundreds of services.
Rotation can be driven by a cron job, a CI pipeline, or a timer managed by systemd. A minimal shell wrapper that a cron entrypoint can call might look like this:
#!/usr/bin/env bash
set -euo pipefail
# Optional: accept a flag to run a single cycle instead of the scheduled loop
if [[ "${1:-}" == "--run-now" ]]; then
exec ./_rotate_one.sh
fi
# Otherwise, loop forever, sleeping between cycles
while true; do
./_rotate_one.sh
sleep 86400 # 24 hours; adjust to your policy
done
Running a single cycle from the command line is then as simple as:
./rotate-secrets.sh --run-now
If you prefer to let the OS manage the schedule, you can define a systemd timer unit and service:
# /etc/systemd/system/secrets-rotation.timer
[Unit]
Description=Run secrets rotation every 12 hours
[Timer]
OnCalendar=*:0/12
Persistent=true
[Install]
WantedBy=timers.target
# /etc/systemd/system/secrets-rotation.service
[Unit]
Description=Execute one secrets‑rotation cycle
[Service]
Type=oneshot
ExecStart=/usr/local/bin/rotate-secrets.sh
Activating the timer is systemctl start secrets-rotation.timer and enabling it across reboots with systemctl enable secrets-rotation.timer.
How you create a new secret depends on its type. For a random string of a fixed length—common for API keys or JWT signing secrets—openssl provides a portable primitive:
NEW_SECRET=$(openssl rand -hex 32)
The output is a 64‑character hex string. If your organization requires a specific charset (e.g., base64url‑encoded 32 bytes), you can pipe through base64 with the -w0 flag to avoid line-wrapping:
NEW_SECRET=$(openssl rand -base64 32 | tr -d '\n')
Many teams store secrets behind a REST‑backed manager rather than plain files. A generic curl POST to generate a new value might look like:
curl -s -X POST https://secrets.example.com/v1/generate \
-H "Authorization: Bearer $AUDIT_TOKEN" \
-H "Content-Type: application/json" \
-d '{"type":"random","length":32}'
Typical responses (shape varies by platform) return the new value and a rotation identifier:
{"secret":"a1b2c3d4e5f6...","rotation_id":"rot-20240827-1"}
If the server rejects the request, you’ll see concrete HTTP errors:
400 Bad Request with "error":"unsupported length" means the length field doesn’t match the manager’s policy.403 Forbidden indicates the bearer token lacks secrets:write scope.422 Unprocessable Entity often appears when the request body is valid JSON but fails schema validation (e.g., missing required type key).The central challenge in rotation is ensuring that all consumers switch to the new value without a window where both old and new are accepted—or neither is. Two patterns are common:
Persist the new secret first, then update every reference in a coordinated batch. If you manage Kubernetes resources, a strategic merge patch can inject the new value into a Secret object:
# Fetch the current Secret definition
kubectl get secret my-app-cred -o yaml > /tmp/current.yaml
# Patch in the new value using sed; this is a stand‑in for whatever
# configuration management tool you use to update consumers.
sed -i 's/old-secret-value/'"$NEW_SECRET"'/' /tmp/current.yaml
# Apply the patch—note that --type=merge performs a strategic merge
# and will drop unmentioned fields unless you also pass the resourceVersion.
kubectl patch secret my-app-cred -p "$(cat /tmp/current.yaml)" --type=merge
Flag gloss:
-p supplies the patch body inline. Without it, kubectl patch reads from stdin.--type=merge is a strategic merge patch; it respects x-kubernetes-list-type annotations and is safer than a raw replace for partial updates.--type defaults to a JSON merge patch, which may overwrite nested maps entirely if you’re not careful.Important: kubectl patch does not restart pods. After the Secret is updated, you must trigger a rollout or explicitly delete pods so they re‑mount the new value:
kubectl rollout restart deployment/my-app
Update all consumer references to point at a new identifier (e.g., a secret name or version label), then persist the value. This pattern is useful when consumers read the secret by name at runtime rather than embedding the raw value. The risk is a gap where consumers look for the new name but the value hasn’t been written yet.
Once consumers have acknowledged the new secret, the old value must be disabled or removed. Leaving an orphaned credential in storage creates a silent attack surface.
curlcurl -s -X DELETE https://secrets.example.com/v1/keys/my-app-key \
-H "Authorization: Bearer $NEW_TOKEN"
Typical responses:
204 No Content — deletion succeeded.409 Conflict — the key is still referenced by an active service map or a dependents field. Some platforms require you to clear references first or supply a cascade=true flag (if supported).410 Gone — the key has already been hard‑deleted past its grace period.If your API supports a TTL or expires_at field on the secret object, you can set it at creation time rather than managing a separate deletion step:
curl -s -X POST https://secrets.example.com/v1/keys \
-H "Authorization: Bearer $AUDIT_TOKEN" \
-H "Content-Type: application/json" \
-d '{"name":"my-app-key","type":"rotating","rotation_ttl":"24h"}'
The server will automatically mark the secret as expired after the window, after which a cleanup job can hard‑delete it. If your platform doesn’t expose a TTL flag, you’ll need to script the expiry yourself: store the rotation_id alongside an expires_at timestamp, and have consumers filter by that field. Attempting to fetch a secret past its expires_at often returns 422 Unprocessable Entity with "error":"secret expired", signalling that the rotation window closed without a successor in place.
If a rotation job runs mid‑deploy, you can end up with half the pod fleet using the old secret and half using the new one. The symptom is intermittent 401 Unauthorized errors that disappear after the next deploy. Fix: gate rotation on a deployment marker (e.g., annotate the Deployment with rotation-in-progress: "true" and have the rotation job exit early if the annotation exists), or synchronize rotation with your CI pipeline’s post‑success hook so the new secret is only published after a deploy is confirmed healthy.
kubectl flagskubectl patch and kubectl apply have overlapping but distinct semantics. --type=merge on patch performs a strategic merge that respects list merging rules; --type=replace (the default for apply) recreates the resource from the supplied manifest. A common mistake is using kubectl apply -f new-secret.yaml --force when only a single key changed, which wipes the entire Secret and breaks all pods immediately. Rule of thumb: for single‑key rotations, prefer kubectl patch -p; reserve apply for full‑resource replacements.
GitHub Actions, GitLab CI, and similar systems cache pipeline artifacts. If your rotation step reads SECRET_FROM_CACHE instead of fetching fresh, the rotation appears to succeed but consumers still hit the old value. The error log will show SECRET_ROTATED while the API returns the previous hash. Fix: explicitly export SECRET= in the job step, never rely on saved output, and use env: { global: false } to force fresh evaluation.
If the job generates the new secret but crashes before updating the consumer config, you’ll have a new secret with no consumer pointing at it, and the old secret still active. The next rotation cycle may then overwrite the new secret thinking it’s the current one, or worse, delete it. Pattern: always output a rotation_status.json with fields new_secret_id, old_secret_id, consumer_updated: true/false, and have a separate reconciliation job that reads this file and blocks further rotations until consumer_updated is true.
Some runtimes cache environment‑variable values at container start. Even after you patch the Secret object, a running pod may still read the old value from /proc/self/environ. There is no kubectl secret refresh flag; the only sure fix is a pod restart. The pattern is: kubectl patch secret … && kubectl annotate pod <pod-name> rotation-completed=$(date +%s) && kubectl rollout restart deployment/my-app.
openssl, or POST to your secrets manager’s API.kubectl patch + kubectl rollout restart for K8s, config‑management tool runs for infrastructure-as-code, or API batch calls for SaaS platforms.Following this flow, documenting each step’s exit conditions, and treating the rotation_status.json as the source of truth for the next iteration will keep secret rotation reliable, auditable, and resistant to the silent failures that typically surface only after a production incident.
This page was rewritten on 12 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy