How to Use Dynamic Secrets from Vault
Issue short-lived, per-instance database credentials from HashiCorp Vault so there are no long-lived passwords to rotate or leak.
On this page
Introduction
A static database password shared across a fleet is a secret with no owner and no expiry. It reaches a dozen configuration files, is copied into a container image or an environment variable, and when it leaks you must rotate it everywhere at once. Dynamic secrets invert this: instead of a password that lives forever, the secret store issues a unique credential to each client on demand, with a lease that expires. When the lease ends, the credential is revoked and the underlying account is dropped. There is nothing long-lived to leak.
Static Versus Dynamic Secrets
A static secret is created once and used by many clients for as long as it is valid. The more clients, the more copies, and the harder rotation becomes. A dynamic secret is created per client, on demand, with a lease. Each instance gets its own credential, so a leak identifies one client and expires soon, and revocation is deleting one account rather than coordinating a fleet-wide rotation.
The secret store authenticates the client before issuing the credential, so the credential is issued only to an identity it trusts. That identity might be a Kubernetes service account, a cloud workload identity, or an AppRole. The trust between the client and the store replaces the trust you used to place in a shared password.
# dynamic database credentials
client (pod, instance) --> authenticate to secret store --> obtain lease
--> store creates a unique DB user for this client
--> returns username + password with a TTL
--> on lease expiry, store drops the DB user
# result: no shared password; a leak affects one client for minutes
Configuring a Dynamic Secret Engine
The secret store needs an admin credential to the database so it can create and drop users. You configure a role that says which SQL statements to run on issue and on revoke, and how long the lease lasts. When a client requests a credential from the role, the store runs the creation statement, returns the new username and password, and schedules the revocation.
Keep the creation and revocation statements balanced: whatever the issue statement creates, the revoke statement must remove. A role whose revoke fails leaves orphaned database users accumulating, which is both a security and an administrative problem. Test revocation explicitly, not just issuance.
# Configure the database engine and a role with creation/revocation SQL.
vault write database/config/appdb \
plugin_name=postgresql-database-plugin \
connection_url="postgresql://{{username}}:{{password}}@db:5432/appdb" \
allowed_roles="app-readwrite"
vault write database/roles/app-readwrite \
db_name=appdb \
creation_statements="CREATE ROLE \"{{name}}\" LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}'; GRANT app_rw TO \"{{name}}\";" \
revocation_statements="DROP ROLE IF EXISTS \"{{name}}\";" \
default_ttl="1h" max_ttl="24h"
Reading a Credential at Runtime
The application authenticates to the secret store using its platform identity, then reads a credential from the role. The response includes a lease id and a lease duration. The application uses the credential and renews the lease before it expires, or obtains a fresh one and rotates it out. Credentials should never be written to disk or baked into an image.
Reading a secret at startup and using it forever defeats the point: the lease will expire and the credential will be revoked while the app keeps trying to use it. The application must treat the credential as ephemeral and be prepared for it to change. This is the operational shift dynamic secrets require.
interface Lease { username: string; password: string; leaseId: string; leaseDuration: number; }
export async function fetchDbCredential(vault: VaultClient, role: string): Promise<Lease> {
const res = await vault.read(`database/creds/${role}`);
return {
username: res.data.username,
password: res.data.password,
leaseId: res.lease_id,
leaseDuration: res.lease_duration,
};
}
// renew well before expiry; do NOT cache the credential indefinitely
export async function renew(vault: VaultClient, leaseId: string) {
return vault.write('sys/leases/renew', { lease_id: leaseId });
}
Lease Renewal and Rotation
A credential is only as good as its lease. Renew the lease at roughly two-thirds of its duration, so a transient failure still leaves time to retry. If renewal fails and the maximum lease is reached, fetch a brand-new credential and swap the connection pool to it, closing connections that use the old credential.
The swap must be graceful. Build a new pool with the new credential, verify it works with a health check, then drain and close the old pool. Do not tear down the working pool before the new one is proven, or a renewal hiccup becomes an outage. This is the same blue-green discipline used for any live credential rotation.
async function rotatePool(current: Pool, vault: VaultClient, role: string) {
const lease = await fetchDbCredential(vault, role);
const next = await createPoolWith(lease.username, lease.password);
await next.query('SELECT 1'); // prove the new credential works
swapActivePool(next); // new connections use the new pool
await current.end(); // drain and close the old one
scheduleRenewal(vault, lease, () => rotatePool(next, vault, role));
}
Revocation on Shutdown
When an instance shuts down cleanly, it should revoke its lease so the credential is removed immediately rather than waiting for expiry. This narrows the window in which a credential for a dead instance is still valid. Handle shutdown signals and revoke before the process exits, with a short timeout so a slow store does not delay termination indefinitely.
For instances that die uncleanly, expiry is the backstop: the lease eventually ends and the credential is revoked. Set lease durations short enough that the backstop is quick, and monitor for orphaned accounts, which indicate that revocation is failing somewhere. A count of database users created by the store that outlive their leases is a useful health metric.
# shutdown sequence
SIGTERM -> stop accepting new work -> drain in-flight requests
-> revoke lease (bounded timeout, e.g. 5s)
-> close pools -> exit
# if revocation fails/times out: lease expiry still revokes eventually
# metric: orphaned_dynamic_accounts (grows => revocation is broken)
Access Control and Audit
The secret store is a high-value target, so its own authentication must be strong: short-lived platform identity tokens rather than a static token, and a separate policy per application so one app can only read its own role. The store should never be reachable from the public internet, and its audit log must be enabled and monitored.
Reads of credentials are auditable events: a sudden spike, an unexpected identity, or a read from an unusual location are all signals. Because the store logs every issuance with the requesting identity and the lease, it gives you an access trail that a shared password never could. Alert on its health, because if the store is down, new instances cannot get credentials.
# policies: least privilege per app
path "database/creds/app-readwrite" { capabilities = ["read"] } # app A only
path "database/creds/analytics-ro" { capabilities = ["read"] } # app B only
# alert on: unknown identity reading creds, issuance spike, store unreachable (new pods stuck)
Common Pitfalls and Conclusion
Do not cache a dynamic credential forever; it will be revoked under you. Do not bake credentials into images or write them to disk. Do not configure a role whose revocation statement does not match its creation statement. Do not make the store a single point of failure without a plan for its outage. And do not forget that dynamic secrets shift complexity from rotation to lease lifecycle management, which must be handled deliberately.
Dynamic secrets replace a long-lived shared password with a per-client credential that expires. Authenticate clients by platform identity, configure a role with balanced create and revoke statements, read and renew leases at runtime, rotate the connection pool gracefully, revoke on shutdown, and enforce least privilege with auditing. The result is that a leaked credential is one client’s, valid for minutes, and revoked automatically.
Sources: HashiCorp Vault: Dynamic secrets, Vault: Database secrets engine, Vault: Lease, renew and revoke.
FAQ
- What happens when a dynamic credential's lease expires?
- The secret store revokes it, which drops the database account it created. The application must renew the lease before expiry or fetch a fresh credential and rotate its connection pool, because the old credential will stop working.
- How is this better than a rotated static password?
- There is no shared secret to leak, each client gets a unique credential, and a leak identifies one client and expires in minutes instead of affecting the whole fleet until the next rotation. Revocation is deleting one account rather than coordinating a fleet-wide change.
Report a problem with this articleOpens a pre-filled issue on GitHub.