HashiCorp Vault for Application Secrets: KV v2, Policies and AppRole

Database passwords, API keys and certificates tend to spread: .env files on laptops, CI variables, config files on servers, sometimes Git history. Every copy is a place they can leak from, and rotating a credential means tracking down all of them.
HashiCorp Vault gives secrets one home with access control, an audit log and, for some backends, credentials that are generated on demand and expire automatically. This guide runs Vault locally, stores an application's configuration in the KV v2 engine, restricts access with a policy, and has a Python app log in with AppRole to read it, without a long-lived token baked into the app.
Why HashiCorp Vault?
Vault is more than an encrypted key-value store:
- Centralized Storage: A single, secure location for all your secrets.
- Dynamic Secrets: Generate on-demand secrets for databases, cloud providers, and more, which automatically expire, reducing the attack surface.
- Data Encryption: All data at rest is encrypted, and Vault handles the encryption/decryption on access.
- Fine-Grained Access Control: Policies define who can access what, down to specific paths and operations.
- Comprehensive Auditing: Every secret access is logged, providing an invaluable audit trail for compliance and incident response.
A licensing note: since 2023 Vault is released under the Business Source License. That allows most internal use but isn't an open-source license. OpenBao is a community fork under the Mozilla Public License with a compatible API, and the commands in this guide work the same way with its bao CLI.
Prerequisites
For this tutorial, you’ll need:
- HashiCorp Vault: Download the appropriate binary for your OS from the official HashiCorp Vault downloads page.
- Python 3 and
hvaclibrary: We'll use Python for our application example. Installhvacusing pip:Bashpip install hvac - Basic understanding of the command line.
Setting Up and Integrating Vault: A Step-by-Step Guide
Let's dive into setting up Vault and integrating it with a simple Python application. We'll run Vault in "dev mode" for simplicity, but the principles scale to production deployments.
Step 1: Start Vault in Development Mode
Open your terminal and navigate to the directory where you downloaded the Vault binary.
vault server -dev -dev-root-token-id="myroottoken"Dev mode runs entirely in memory (everything is lost on restart), starts already unsealed, listens without TLS on 127.0.0.1:8200, and uses the root token you specified. It's ideal for learning and never for production, where Vault runs with persistent storage, TLS, and a real unseal process.
Step 2: Authenticate to Vault
Open a new terminal window. We need to tell our CLI where Vault is and authenticate.
export VAULT_ADDR='http://127.0.0.1:8200'
vault login myroottokenYou should see "Success! You are now authenticated."
Step 3: Enable and Configure a Key-Value Secrets Engine
Dev mode already mounts a KV version 2 engine at secret/. To mount your own at a clearer path:
vault secrets enable -path=apps -version=2 kvKV v2 keeps a history of each secret (10 versions by default), so you can see what changed and roll back a bad update.
Step 4: Write a Secret
Let's store a mock database credential.
vault kv put -mount=apps myapp/config db_username="app_user" db_password="change-me" api_key="abc-123-xyz"Values typed on the command line end up in your shell history. For real secrets, read them from a file or stdin instead, for example vault kv put -mount=apps myapp/config db_password=@password.txt.
Step 5: Read a Secret
You can read the secret using the CLI to verify.
vault kv get -mount=apps myapp/configYou'll see output like:
==== Data ====
Key Value
--- -----
api_key abc-123-xyz
db_password change-me
db_username app_userStep 6: Create an Access Policy for Your Application
To enforce least privilege, we'll create a policy that grants read-only access to our application's secrets.
First, create a policy file named myapp-policy.hcl:
path "apps/data/myapp/*" {
capabilities = ["read"]
}Now, write this policy to Vault:
vault policy write myapp-reader myapp-policy.hclNote the data/ segment. The CLI's vault kv commands hide it, but KV v2 stores secret values under <mount>/data/<path> and metadata under <mount>/metadata/<path>, and policies must use the real API path. A policy for apps/myapp/* (without data/) is the most common reason an app gets "permission denied" on a secret that exists.
Step 7: Give the Application an Identity with AppRole
Handing the app a token created with vault token create works for a quick test, but then that token becomes one more long-lived secret to protect and rotate. Instead, Vault's auth methods let an app prove who it is and receive a short-lived token. On Kubernetes, AWS, GCP or Azure, use the matching auth method so the platform's own identity is the credential. Everywhere else, AppRole is the general-purpose option:
vault auth enable approle
vault write auth/approle/role/myapp \
token_policies="myapp-reader" \
token_ttl=15m \
token_max_ttl=1h \
secret_id_ttl=24h
# The role ID identifies the app (not secret, like a username)
vault read -field=role_id auth/approle/role/myapp/role-id
# The secret ID is the credential; generate one per deployment
vault write -f -field=secret_id auth/approle/role/myapp/secret-idThe app exchanges the role ID and secret ID for a token that expires after 15 minutes (renewable up to an hour). Deliver the secret ID to the app through your deployment system, and give it a short lifetime or a limited number of uses (secret_id_num_uses), so a leaked one is quickly useless.
Step 8: Integrate Vault into a Python Application
# app.py
import os
import hvac
client = hvac.Client(url=os.environ["VAULT_ADDR"])
# Log in with AppRole; hvac stores the returned token on the client
client.auth.approle.login(
role_id=os.environ["VAULT_ROLE_ID"],
secret_id=os.environ["VAULT_SECRET_ID"],
)
response = client.secrets.kv.v2.read_secret_version(
mount_point="apps",
path="myapp/config",
raise_on_deleted_version=True,
)
config = response["data"]["data"]
# Use the values; never print or log them
db_dsn = f"postgresql://{config['db_username']}:{config['db_password']}@db.internal/app"
print("Loaded configuration keys:", sorted(config))Errors (a wrong secret ID, a policy that doesn't cover the path) raise hvac.exceptions.Forbidden or InvalidRequest. Let them crash the app at start-up rather than running with missing configuration.
Step 9: Run the Python Application
Now, run the Python script.
export VAULT_ADDR=http://127.0.0.1:8200
export VAULT_ROLE_ID=<role id from step 7>
export VAULT_SECRET_ID=<secret id from step 7>
python app.pyThe output lists the keys (api_key, db_password, db_username) without their values.
💡 Tip: If you'd rather not add Vault code to every application, run Vault Agent next to the app (as a sidecar or system service). It handles login and token renewal, and renders secrets into a file or environment variables that the app reads like ordinary config. On Kubernetes, the Vault Secrets Operator can sync secrets into native Kubernetes Secrets.
⚠️ Common mistake: Using the root token in applications or CI because it "just works". The root token can do anything, including reading every secret and changing policies. After initial setup, revoke it (
vault token revoke <token>) and use auth methods with narrow policies for both people and machines.
Next Step: Dynamic Database Credentials
Storing a static database password in KV is an improvement, but the password still lives forever. Vault's database secrets engine goes further: it creates a database user on request, with a TTL, and deletes it when the lease expires. Each app instance gets its own credentials, they rotate automatically, and the audit log shows exactly which instance used which user. It's worth exploring once the basics above are in place.
Summary
- Store application configuration in KV v2 under a per-app path, and remember the
data/segment in policy paths. - Grant least privilege with a policy that only reads the paths an app needs.
- Authenticate apps with an auth method (AppRole, or your platform's Kubernetes or cloud method) that issues short-lived tokens, not static tokens.
- Never print, log or commit secret values, and revoke the root token after setup.
- Move to dynamic secrets for databases when you're ready, so credentials expire on their own.
