Dynamic Database Credentials for PostgreSQL & SQL Server
Most applications connect to databases using a single static username and password stored in a config file or environment variable. If that password leaks in a log file, a Git repository, or a compromised container, an attacker has permanent access until a human manually rotates it.
HashiCorp Vault solves this by generating short-lived database usernames and passwords on demand. Every app instance or developer gets a unique credential with a strict Time-To-Live (TTL). When the lease expires, Vault automatically deletes the user from PostgreSQL or SQL Server.
- Why static database passwords fail in modern cloud and microservice architectures.
- How Vault generates, tracks, and revokes short-lived credentials automatically.
- How to run a complete local hands-on lab using Docker with Vault, PostgreSQL, and SQL Server.
- How to enable the Vault database secrets engine and configure dynamic roles with short TTLs.
- How to request temporary credentials via
vault readand verify login before and after lease revocation. - Real-world production trade-offs like connection pooling, lease renewal, and root credential rotation.
1. Static vs. Dynamic Database Credentials
With static credentials, every microservice instance shares the same database login. If something goes wrong, your audit logs only show that app_user ran a destructive query—you have no idea which container, service, or developer was responsible.
Dynamic credentials flip this model. Vault creates a brand-new database user right when it is requested, attaches a lease timer, and removes the user automatically when the timer hits zero.
| Feature | Static Credentials | Dynamic Credentials (Vault) |
|---|---|---|
| Lifespan | Months or years until manually rotated | Minutes or hours (controlled by Lease TTL) |
| Blast radius if leaked | High — attacker keeps access indefinitely | Minimal — credentials expire automatically |
| Audit trail | Shared login across all instances | Unique username per request/instance |
| Revocation | Manual password change + app restarts | Instant via vault lease revoke or TTL expiry |
2. How Dynamic Credentials Work Under the Hood
Vault acts as a trusted broker between your application and your database. You give Vault a single privileged admin connection once, and Vault uses it to mint and destroy temporary accounts on demand.
Dynamic Database Credential Lifecycle (Vault + PostgreSQL / SQL Server)
Vault creates a unique database login on demand, returns it to the app, and automatically drops the user from the database when the lease TTL expires.
readonly-role).CREATE USER statement with a randomly generated username and password.lease_id to your application. Your app connects directly to the database.3. Hands-On Lab: Start Local Containers
Let's build this locally using Docker. You will start a Vault dev server and either a PostgreSQL container, a SQL Server container, or both.
Create a shared Docker network
Step 1: Create a Docker network so Vault can reach the databases
docker network create vault-db-net
Start HashiCorp Vault (Dev Mode)
Step 2: Start Vault in dev mode
docker run -d --name vault-dev --network vault-db-net \
-p 8200:8200 \
-e VAULT_DEV_ROOT_TOKEN_ID=root \
-e VAULT_DEV_LISTEN_ADDRESS=0.0.0.0:8200 \
hashicorp/vault:latest
Set your local terminal environment variables so the Vault CLI talks to your container:
Configure Vault CLI environment
export VAULT_ADDR="http://127.0.0.1:8200"
export VAULT_TOKEN="root"
$env:VAULT_ADDR="http://127.0.0.1:8200" and $env:VAULT_TOKEN="root" instead of export.Start PostgreSQL or SQL Server
Option A: Start a local PostgreSQL container
docker run -d --name postgres-db --network vault-db-net \
-p 5432:5432 \
-e POSTGRES_USER=vaultadmin \
-e POSTGRES_PASSWORD=SuperSecretAdminPass! \
-e POSTGRES_DB=appdb \
postgres:16
Option B: Start a local SQL Server container
docker run -d --name sqlserver-db --network vault-db-net \
-p 1433:1433 \
-e ACCEPT_EULA=Y \
-e MSSQL_SA_PASSWORD="SuperSecretAdminPass!123" \
mcr.microsoft.com/mssql/server:2022-latest
4. Enable the Vault Database Secrets Engine
Before configuring any database, you must enable the database secrets engine inside Vault. You can run commands directly from your host if you have the Vault CLI installed, or via docker exec -e VAULT_ADDR=http://127.0.0.1:8200 -e VAULT_TOKEN=root vault-dev vault ....
Enable the database secrets engine
vault secrets enable database
Expected output
Success! Enabled the database secrets engine at: database/
5. Configure PostgreSQL Dynamic Credentials
First, register the PostgreSQL connection with Vault using the postgresql-database-plugin. Notice we use the container name postgres-db as the hostname because both containers share vault-db-net.
Step 1: Configure Vault to connect to PostgreSQL
vault write database/config/my-postgres \
plugin_name=postgresql-database-plugin \
allowed_roles="pg-readonly" \
connection_url="postgresql://{{username}}:{{password}}@postgres-db:5432/appdb?sslmode=disable" \
username="vaultadmin" \
password="SuperSecretAdminPass!"
Next, create a dynamic role named pg-readonly with a short 1-minute default TTL and a 5-minute maximum TTL. Vault replaces {{name}}, {{password}}, and {{expiration}} automatically at runtime.
Step 2: Create a dynamic PostgreSQL role with a 1-minute TTL
vault write database/roles/pg-readonly \
db_name=my-postgres \
creation_statements="CREATE ROLE \"{{name}}\" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}'; \
GRANT SELECT ON ALL TABLES IN SCHEMA public TO \"{{name}}\";" \
revocation_statements="DROP ROLE IF EXISTS \"{{name}}\";" \
default_ttl="1m" \
max_ttl="5m"
Expected output
Success! Data written to: database/roles/pg-readonly
6. Configure SQL Server Dynamic Credentials
SQL Server uses the mssql-database-plugin. Because SQL Server separates server-level Logins from database-level Users, your creation statement creates both, and your revocation statement cleans up both.
Step 1: Configure Vault to connect to SQL Server
vault write database/config/my-mssql \
plugin_name=mssql-database-plugin \
allowed_roles="mssql-readonly" \
connection_url="sqlserver://{{username}}:{{password}}@sqlserver-db:1433" \
username="sa" \
password="SuperSecretAdminPass!123"
Step 2: Create a dynamic SQL Server role with a 1-minute TTL
vault write database/roles/mssql-readonly \
db_name=my-mssql \
creation_statements="CREATE LOGIN [{{name}}] WITH PASSWORD = '{{password}}'; \
USE master; \
CREATE USER [{{name}}] FOR LOGIN [{{name}}]; \
ALTER ROLE db_datareader ADD MEMBER [{{name}}];" \
revocation_statements="USE master; \
DROP USER IF EXISTS [{{name}}]; \
DROP LOGIN [{{name}}];" \
default_ttl="1m" \
max_ttl="5m"
Expected output
Success! Data written to: database/roles/mssql-readonly
7. Request Temporary Credentials & Test Login
Now request a fresh set of credentials using vault read. Every time you run this command, Vault generates a completely different username and password.
Request PostgreSQL credentials (or use database/creds/mssql-readonly for SQL Server)
vault read database/creds/pg-readonly
Expected output
Key Value --- ----- lease_id database/creds/pg-readonly/8f3a9c12b4e5f6a7c8d9e0f1 lease_duration 1m lease_renewable true password A1b2-C3d4E5f6G7h8I9j0 username v-root-pg-reado-9x8y7z6w-1732684800
Test login BEFORE lease revocation
Copy the generated username and password and test logging in immediately.
Test PostgreSQL login via Docker
docker exec -it -e PGPASSWORD="A1b2-C3d4E5f6G7h8I9j0" postgres-db \
psql -U "v-root-pg-reado-9x8y7z6w-1732684800" -d appdb -c "SELECT current_user, now();"
Expected output (Login succeeds)
current_user | now
---------------------------------------+-------------------------------
v-root-pg-reado-9x8y7z6w-1732684800 | 2026-11-27 05:30:12.481922+00
(1 row)
Test SQL Server login via Docker (if using SQL Server)
docker exec -it sqlserver-db /opt/mssql-tools18/bin/sqlcmd \
-S localhost -U "v-root-mssql-re-..." -P "GeneratedPass" -C \
-Q "SELECT SYSTEM_USER AS CurrentLogin;"
8. Revoke the Lease & Verify Access Is Blocked
You can either wait 60 seconds for the 1m TTL to expire automatically, or revoke the lease immediately using the lease_id returned earlier.
Manually revoke the lease immediately
vault lease revoke database/creds/pg-readonly/8f3a9c12b4e5f6a7c8d9e0f1
Expected output
All revocation operations queued successfully!
Test login AFTER lease revocation
Run the exact same login command again with the revoked credentials:
Re-test PostgreSQL login
docker exec -it -e PGPASSWORD="A1b2-C3d4E5f6G7h8I9j0" postgres-db \
psql -U "v-root-pg-reado-9x8y7z6w-1732684800" -d appdb -c "SELECT current_user;"
Expected output (Access denied)
psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: role "v-root-pg-reado-9x8y7z6w-1732684800" does not exist
The temporary user is completely gone. Even if an attacker stole those credentials 30 seconds ago, they are now useless.
9. Architecture & Real-World Trade-offs
Enabling dynamic credentials in production requires thinking beyond the basic CLI commands. Here is what matters at scale:
- Connection Pooling & Lease Renewal: Databases like PostgreSQL and SQL Server keep existing connections open even after a password expires, or drop them abruptly during revocation. Your application (or a sidecar like Vault Agent) must renew the lease before it hits 70–80% of its TTL, and gracefully rebuild the connection pool when
max_ttlis reached. - Rotate the Root Credential Immediately: Right after running
vault write database/config/..., runvault write -f database/rotate-root/my-postgres. This makes Vault change the admin password so that not even the DevOps engineer who set it up knows the root password anymore. - PostgreSQL Object Ownership Trap: If a dynamic user creates a table in PostgreSQL, Vault cannot drop that user later because the user owns database objects. Always grant dynamic roles
SELECT/INSERT/UPDATE/DELETEonly, or useSET ROLEto a shared owner role before creating objects. - Vault High Availability: Because your apps depend on Vault to fetch new credentials on startup and renewal, run Vault in an HA cluster (Integrated Storage / Raft) across multiple availability zones.
VAULT_DEV_ROOT_TOKEN_ID=root) in staging or production. Dev mode stores everything in memory without TLS encryption and loses all data when the container restarts.10. Hands-On Practice
Request a new credential from database/creds/pg-readonly. Do not run vault lease revoke. Log in immediately to verify it works, wait 65 seconds, and try logging in again.
Hint: Watch the Vault container logs using docker logs -f vault-dev to see Vault revoke the lease automatically.
Create a second Vault role named pg-readwrite with a default_ttl="2m" that grants SELECT, INSERT, UPDATE on all tables in the public schema.
Expected result: Update allowed_roles in database/config/my-postgres to include pg-readwrite, then verify you can read credentials from it.
Trigger Vault's root rotation endpoint on your PostgreSQL or SQL Server configuration so the original SuperSecretAdminPass! password stops working.
Hint: Use vault write -f database/rotate-root/my-postgres and then try logging in with the old admin password to confirm it fails.
11. Interview Questions
Answer: When the lease expires, Vault executes the revocation statement (dropping the user or login). New connections immediately fail. In PostgreSQL, an already-open session may continue briefly unless the revocation statement also calls pg_terminate_backend() for that user's active sessions.
Answer: Applications use a lease-renewal loop or Vault Agent to extend the lease up to max_ttl. Before max_ttl expires, the app fetches a brand-new credential pair, initializes a new database connection pool with it, and drains the old pool gracefully.
rotate-root after configuring the Vault database secrets engine?
Answer: During initial setup, a human or CI/CD pipeline provides the admin password to Vault. Running rotate-root forces Vault to generate a new random password that only Vault knows, eliminating human access to the privileged database account.
default_ttl and max_ttl in a Vault database role?
Answer: default_ttl is the initial lifespan of a newly generated credential. max_ttl is the hard upper limit—even if an application keeps renewing the lease, Vault will force-revoke the credential once max_ttl is reached.
Conclusion
Dynamic database credentials eliminate one of the oldest and most dangerous security weaknesses in backend engineering: long-lived static passwords. By pairing HashiCorp Vault with PostgreSQL or SQL Server, every login becomes short-lived, traceable, and self-cleaning.
Start by running this local Docker lab, practice revoking leases, and then explore integrating Vault Agent or native Vault SDKs into your .NET, Python, or Node.js services.
Official Documentation
- HashiCorp Vault Documentation – Database Secrets Engine
- HashiCorp Vault Documentation – PostgreSQL Database Secrets Engine
- HashiCorp Vault Documentation – Microsoft SQL Server Database Secrets Engine
Upgradix by Shrash Studio – Learn Technology. Build Your Future.
Discussion & Comments
0No comments yet
Start the discussion above — ask a question, share a tip, or reply to a comment.