How to Rotate Secrets Automatically with Vault
Use Vault's database secrets engine to issue short-lived, automatically rotating database credentials with leases. Covers configuring the engine, reading dynamic creds, and renewing or revoking leases.
What and why
Long-lived static credentials are a major breach risk. HashiCorp Vault's dynamic secrets engine generates short-lived, on-demand credentials with a lease. When the lease expires (or you revoke it), Vault deletes the credential at the source. Applications get fresh credentials and never hold long-lived secrets.
Prerequisites
- A running database (PostgreSQL here).
- Docker installed.
- Vault CLI available.
Steps
1. Run Vault in dev mode
docker run --cap-add=IPC_LOCK -p 8200:8200 -e VAULT_DEV_ROOT_TOKEN_ID=root hashicorp/vault
export VAULT_ADDR=http://localhost:8200 VAULT_TOKEN=root
Dev mode is for learning only; never use it in production.
2. Enable the database secrets engine
vault secrets enable database
3. Configure the database connection
vault write database/config/appdb \
plugin_name=postgresql-database-plugin \
connection_url='postgresql://{{username}}:{{password}}@db:5432/app?sslmode=disable' \
allowed_roles='reader' \
username='vault_admin' password='admin_pw'
Vault uses an admin account only to create and drop the short-lived users.
4. Create a role with a TTL
vault write database/roles/reader \
db_name=appdb \
creation_statements="CREATE ROLE \"{{name}}\" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}'; GRANT SELECT ON ALL TABLES IN SCHEMA public TO \"{{name}}\";" \
default_ttl=1h max_ttl=24h
5. Read dynamic credentials
vault read database/creds/reader
Vault returns a unique username, password, and lease ID. The application uses these for up to the TTL.
6. Renew and revoke leases
Renew a lease before it expires:
vault lease renew database/creds/reader/<lease_id>
Or revoke immediately on compromise:
vault lease revoke database/creds/reader/<lease_id>
Revocation drops the database user, instantly invalidating the credential.
Verification
vault read database/creds/readerreturns working credentials.- The new user exists in the database and can run SELECT.
- After revocation, the user is gone and login fails.
Next Steps
Give applications a Vault auth method (Kubernetes, AppRole) instead of a root token, use the Vault Agent to auto-renew leases, and apply the same pattern to cloud IAM, message brokers, and API keys.
Prerequisites
- A running database
- Docker installed
- Basic CLI knowledge
Steps
- 1Run Vault in dev mode
- 2Enable the database secrets engine
- 3Configure the database connection
- 4Create a role with a TTL
- 5Read dynamic credentials
- 6Renew and revoke leases