Join our Newsletter — 33% off our NHI Course
Home› Guides› How to set up Vault database dynamic credentials:…
Guide Secrets Management

How to set up Vault database dynamic credentials: Per-app, time-limited database users for PostgreSQL, MySQL and SQL Server

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 18 November 2026 15 min read
On this page

HashiCorp Vault's database secrets engine replaces shared, long-lived database passwords with a unique database user for each application instance, created on demand and dropped when its lease ends. That single change removes the most common database non-human identity problem: one service account password copied into config files, CI variables and laptops, never rotated because nobody knows what would break.

This guide is the hands-on companion to our Dynamic Secrets and Ephemeral Credentials Guide, which explains the concept. Here we set up the engine for PostgreSQL, MySQL and MariaDB, and Microsoft SQL Server: the Vault management account, connection configuration, root rotation, role design with least-privilege creation and revocation statements, lease lifetimes, client consumption and emergency revocation.

This is an independent guide from NHI Mgmt Group, based on HashiCorp's public documentation as of November 2026. It is not sponsored or reviewed by HashiCorp. Product features change, so confirm settings against HashiCorp's current documentation.

Key takeaways

  • The database secrets engine creates a new database user per request from SQL you supply, and revokes it automatically when the lease expires.
  • Create a dedicated database account for Vault to manage users, then rotate its password with rotate-root so only Vault knows it.
  • Use allowed_roles on each connection so only the intended Vault roles can use it.
  • Write one Vault role per application and privilege level, with creation statements that grant only what the application needs. Never grant *.* or ownership.
  • Keep default_ttl short (HashiCorp's examples use 1 hour) and set a max_ttl so a credential cannot be renewed forever.
  • Write explicit revocation statements where the default procedure cannot find the users, and test revocation, not just creation.
  • Lease IDs start with the role path, so vault lease revoke -prefix can kill every credential for a role in one command during an incident.

How dynamic database credentials work

HashiCorp describes the engine as one that generates database credentials dynamically based on configured roles, so that services no longer need to hardcode credentials. Three objects make it work:

  • Connection (database/config/<name>): which plugin to use, the connection URL, the management account and which roles may use it.
  • Role (database/roles/<name>): which connection it uses, the SQL to create and remove a user, and the lease lifetimes.
  • Lease: created on every read of database/creds/<role>. HashiCorp states that all dynamic secrets in Vault are required to have a lease, and that when the lease expires Vault can automatically revoke the data.

A client with a Vault token and a policy allowing read on database/creds/payments-ro receives a username, a password, a lease_id and a lease_duration. Vault has already run the creation statements in the database. When the lease ends, or when someone revokes it, Vault runs the revocation statements and the user disappears.

The audit benefit is direct. HashiCorp notes that because every service accesses the database with unique credentials, questionable data access can be traced to the specific instance of a service from the SQL username. Generated names include the role and a random suffix, such as v-vaultuse-my-role-x on PostgreSQL or v_vaultuser_my-role_crBWVqVh2Hc1 on MySQL.

The engine also supports static roles, a one-to-one mapping to an existing database user whose password Vault rotates on a schedule. Static roles help with legacy applications that cannot handle a changing username, but anyone with the right Vault policy gets the same account, so they do not give per-instance attribution. This guide focuses on dynamic roles and uses static roles only where noted.

Step 1: Create a dedicated Vault management account

HashiCorp highly recommends creating a database user specifically for Vault to use, which the documentation calls the "root" user. Vault uses it to create, update and revoke credentials, so it needs rights to manage other users, but it should not be your real superuser or the DBA's account.

PostgreSQL

Create a login role such as vault_mgr with CREATEROLE and the ability to grant the specific privileges your application roles need, for example by making it the owner of, or a member with grant option on, a set of group roles. A pattern that keeps grants simple is to create group roles such as app_payments_ro and app_payments_rw that hold the table privileges, and have Vault's creation statements only grant membership of one of them. Vault never needs SUPERUSER for this.

MySQL and MariaDB

Create a vault_mgr account with CREATE USER and the specific privileges it will grant, held WITH GRANT OPTION and scoped to the application schemas. Avoid giving it ALL PRIVILEGES ON *.*. Restrict the account's host part to the Vault servers' addresses rather than '%'.

SQL Server

HashiCorp lists the minimum privileges for the MSSQL plugin: a login and user for Vault, with ALTER ANY LOGIN and ALTER ANY USER, ALTER ANY CONNECTION, VIEW ANY DEFINITION, VIEW SERVER STATE, VIEW DEFINITION, CONTROL ON SCHEMA::<schema_name> and membership of db_accessadmin. The documentation also names the fixed roles securityadmin, processadmin, db_accessadmin and db_securityadmin as examples that grant the needed permissions. Prefer the explicit grant list over fixed server roles, because securityadmin can grant itself far more than Vault needs. Vault's MSSQL support uses SQL authentication; for Azure SQL Database HashiCorp notes that Azure AD authentication is not supported and you need a separate connection and role for each contained database.

Whatever the engine, record the management account as a privileged non-human identity with a named owner, and alert on any interactive login with it. See our Database Credential and Access Security Guide for the wider controls around such accounts.

Step 2: Enable the engine and configure connections

Enable the engine with vault secrets enable database, or use -path to mount it elsewhere, for example one mount per environment such as db-prod and db-test. Separate mounts make policies and prefix revocation cleaner.

Then write one connection per database. Examples based on HashiCorp's documentation:

EnginePlugin nameExample connection URL
PostgreSQLpostgresql-database-pluginpostgresql://{{username}}:{{password}}@db.internal:5432/payments?sslmode=verify-full
MySQL / MariaDBmysql-database-plugin (also mysql-aurora-database-plugin, mysql-rds-database-plugin, mysql-legacy-database-plugin){{username}}:{{password}}@tcp(db.internal:3306)/
SQL Servermssql-database-pluginsqlserver://{{username}}:{{password}}@db.internal:1433

The MySQL plugin variants differ only in the length of the usernames they generate, because MySQL versions accept different lengths, so pick the one that matches your server.

Settings to get right on every connection:

  • allowed_roles: list the Vault roles that may use this connection. Avoid *, or any role author can point a new role at your production database.
  • username and password: the management account from Step 1. The {{username}} and {{password}} placeholders in the URL are filled from these.
  • TLS: require encryption. The PostgreSQL plugin uses the pgx library and accepts sslmode=verify-full and client certificate options (private_key, tls_certificate, tls_ca). The MySQL plugin accepts tls_certificate_key and tls_ca.
  • password_authentication on PostgreSQL: HashiCorp's example sets scram-sha-256.
  • Password policy: by default Vault generates 20-character passwords with at least one uppercase letter, lowercase letter, number and dash. You can set a stronger password policy per connection or per role.

Step 3: Rotate the root credential so only Vault knows it

Straight after configuring a connection, HashiCorp strongly recommends rotating the management password so the account is not accessible by anyone other than Vault:

vault write -force database/rotate-root/payments-pg

After this the password you typed in Step 2 no longer works, which is the point: it is no longer in a ticket, a shell history or a password manager. This is also why HashiCorp recommends a dedicated account; if you rotate an account humans use, you lock them out.

Two cautions from the documentation:

  • Do not manage the root credential with a static role. Vault does not distinguish between root and standard credentials when rotating, so if you assign the config/ account to a static role, every dynamic and static user on that connection fails after rotation. Use the rotate-root endpoint instead.
  • Scheduled root rotation using rotation_schedule and rotation_window is an Enterprise feature. On Community Edition, run rotate-root from your own scheduler and record each run.

On MySQL 5.6, root rotation needs root_rotation_statements using the older SET PASSWORD syntax, because the default uses ALTER USER from MySQL 5.7.

Step 4: Design least-privilege roles

A role is where you decide what each generated user can do. HashiCorp's examples deliberately keep the SQL short, and in two of them the grants are wider than most applications need: GRANT SELECT ON ALL TABLES IN SCHEMA public on PostgreSQL and GRANT SELECT ON *.* on MySQL. Treat these as syntax examples, not templates.

Role design rules

  1. One role per application and privilege level, such as payments-ro and payments-rw. Shared roles hide which service did what.
  2. Grant membership of a pre-built group role instead of table-by-table grants in the creation statement. Privilege changes then happen in the database through normal change control, and every new dynamic user picks them up.
  3. No ownership, no DDL for application roles. A dynamic user that owns objects cannot be cleanly dropped, and revocation fails.
  4. Use the expiry placeholder where supported. On PostgreSQL, VALID UNTIL '{{expiration}}' makes the database itself refuse the password after the lease time, a useful backstop if revocation fails.

Example roles

PostgreSQL, granting a group role:

vault write database/roles/payments-ro db_name=payments-pg creation_statements="CREATE ROLE \"{{name}}\" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}' IN ROLE app_payments_ro;" default_ttl=1h max_ttl=8h

MySQL, scoped to one schema:

vault write database/roles/payments-ro db_name=payments-mysql creation_statements="CREATE USER '{{name}}'@'10.20.%' IDENTIFIED BY '{{password}}'; GRANT SELECT ON payments.* TO '{{name}}'@'10.20.%';" default_ttl=1h max_ttl=8h

HashiCorp notes that MySQL wildcard grants inside backticks, such as `fooapp\_%`.*, are interpreted by the shell, so encode such statements in Base64 when writing them through the CLI. Use wildcard database grants sparingly; each one widens what a stolen credential reaches.

SQL Server, login plus database user with a schema grant:

vault write database/roles/payments-ro db_name=payments-mssql creation_statements="CREATE LOGIN [{{name}}] WITH PASSWORD = '{{password}}'; USE payments; CREATE USER [{{name}}] FOR LOGIN [{{name}}]; ALTER ROLE app_payments_ro ADD MEMBER [{{name}}];" default_ttl=1h max_ttl=8h

Before using ALTER ROLE ... ADD MEMBER on busy SQL Server databases, read HashiCorp's warning: it takes a schema modification lock that blocks all operations, including reads, and can cause temporary deadlocks during credential operations. If that is a problem, grant directly on the schema instead.

Step 5: Write and test revocation statements

Revocation is what makes credentials dynamic, and it is the part teams test least. If you do not set revocation_statements, Vault runs the plugin's default procedure. On SQL Server, HashiCorp warns that the default uses a metadata query scoped to the database in connection_url. If your creation statements add users in a different database, Vault cannot detect or remove them, and in larger databases the default can time out. Write an explicit revocation statement in that case.

Example revocation statements:

  • PostgreSQL: revoke group membership, reassign or drop owned objects if any can exist, then DROP ROLE IF EXISTS "{{name}}";
  • MySQL: DROP USER IF EXISTS '{{name}}'@'10.20.%'; with the same host part used at creation.
  • SQL Server: drop the database user in each database where it was created, kill its sessions if your policy requires it, then DROP LOGIN [{{name}}];. HashiCorp's Azure SQL example uses DROP USER IF EXISTS [{{name}}].

Test it: request a credential, connect with it, revoke the lease and confirm the user is gone from the database catalogue. Then check what happens to an open session. Dropping a login does not always end existing connections, so decide whether your revocation statements should terminate sessions, and test that too. Repeat the test after every database version upgrade.

Step 6: Set lease lifetimes and consume credentials safely

Each role sets default_ttl and max_ttl. HashiCorp's examples use 1 hour and 24 hours, and the GUI defaults are the same. Our recommendations:

  • Services: 1 hour default, 4 to 8 hours maximum. Clients renew while running and request a new credential when the maximum is reached.
  • Batch jobs: a default slightly longer than the expected run, with a maximum just above the worst case.
  • Humans running queries: a separate read-only role with 15 to 60 minutes, behind stronger Vault authentication.

When a client renews, it can request an increment. HashiCorp explains that the increment counts from the current time, not from the end of the current lease, and that the engine may ignore it, so clients must read the new lease duration from the response rather than assume it. Clients also have to cope with a username change when the maximum lifetime is reached: connection pools should drain and reconnect with the new credential rather than fail.

How the application gets the credential matters as much as the credential. A Vault Agent or sidecar that writes credentials to a memory-backed file, or a client library that requests and renews in process, keeps the password out of environment variables, images and logs. The application's own Vault login should use a platform identity rather than a static token; for Kubernetes, see How to set up HashiCorp Vault Kubernetes auth.

Give each application a Vault policy allowing only read on its own database/creds/<role> path. Keep database/config/*, database/roles/* and database/rotate-root/* for administrators.

Step 7: Monitor and respond

Dynamic credentials give you two audit trails that can be joined: Vault's audit device records which Vault identity read which role and the lease ID issued, and the database logs record what the generated username did. Collect both and join them on the username.

Detections worth building:

  • Logins from the management account from anywhere other than Vault servers.
  • Generated v- or v_ usernames still present in the database after their lease should have ended, which means revocation is failing.
  • A role issuing far more credentials than usual, which may mean a client is not reusing or renewing leases, or that a stolen Vault token is being used.
  • Changes to connection or role configuration outside change control, especially widened allowed_roles or new grants in creation statements.

For incident response, lease IDs are structured so their prefix is always the path the secret came from. HashiCorp gives the example vault lease revoke -prefix aws/; the same approach applies here. To kill every live credential for one role, run vault lease revoke -prefix database/creds/payments-ro. To cut off a whole mount, revoke database/. Revoking a Vault token also revokes all leases created with it. After a suspected compromise, also rotate the management account with rotate-root.

These controls address MITRE ATT&CK T1078 Valid Accounts and T1552.001 Credentials In Files, the two routes by which shared database passwords are usually abused, and they support NIST SP 800-53 AC-2 Account Management and IA-5 Authenticator Management.

Common failure patterns

  • Superuser as the Vault account. Vault manages users with the DBA's or the cloud provider's master account, so a Vault compromise is a full database compromise.
  • Root password never rotated. rotate-root was skipped, so the management password still sits in a runbook or a Terraform state file.
  • Copied example grants. GRANT SELECT ON *.* or all tables in public left in production roles.
  • allowed_roles="*" on production connections.
  • Revocation never tested. Users pile up because the default procedure cannot see them, or dropped logins keep open sessions.
  • Long or unbounded leases. A 30-day default TTL makes dynamic credentials behave like static ones.
  • Static roles for everything. Teams choose static roles to avoid username changes and lose per-instance attribution.
  • Credential written to environment variables or logs by the consuming application, undoing the short lifetime.
  • Static Vault token in the application, so the database credential is dynamic but the credential that fetches it is not.

Practitioner checklist

  • Dedicated management account per database with only the rights to manage users and grant application group roles.
  • rotate-root run after configuration and on a recorded schedule.
  • Each connection lists explicit allowed_roles and enforces TLS.
  • One Vault role per application and privilege level, granting a pre-built group role.
  • No *.*, ownership or DDL grants in application creation statements.
  • Explicit revocation statements written and tested, including open-session behaviour.
  • default_ttl one hour or less for services, with max_ttl set.
  • Clients renew leases, handle username changes and never log or export credentials.
  • Application Vault policies limited to read on their own creds path.
  • Vault audit and database logs joined on generated username, with alerts on lingering users and management account use.
  • Prefix revocation command documented in the incident runbook for every role.

Standards and references

Related NHI Mgmt Group resources: Dynamic Secrets and Ephemeral Credentials Guide · HashiCorp Vault Guide · How to rotate database credentials without downtime · Database Credential and Access Security Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.