Intekhab Rizvi

Chapter 17 / 28

Dynamic Secrets with MongoDB

HashiCorp Vault For Beginners8 min read

MongoDB is a widely-used NoSQL database. In this chapter, we’ll configure Vault to dynamically generate credentials for MongoDB, so users or apps never need to know the database root credentials. Vault will create, manage, and revoke them on demand.

Step 0: Clean Up Previous Setup

Before we begin, let’s make sure no conflicting containers are running from our previous exercises.

Run:

docker compose down

This will stop and remove all existing containers. We’re starting fresh.

To speed up the hands-on experience, we've already created the docker-compose.yml files for you and placed them inside the chapter-17 folder. Make sure to go inside the chapter-17 folder before executing the docker compose up -d command.

Step 1: Docker Compose Setup (Vault + MongoDB)

Let’s set up our environment. Create a docker-compose.yml file with the following content:

services:
  vault-dev:
    image: hashicorp/vault:latest
    container_name: vault-dev
    ports:
      - "8200:8200"
    environment:
      VAULT_DEV_LISTEN_ADDRESS: "0.0.0.0:8200"
    volumes:
      - ../vault-data/config:/vault/config
      - ../vault-data/file:/vault/file
      - ../vault-data/logs:/vault/logs
      - ../:/home/vault/vault-beginner
    cap_add:
      - IPC_LOCK
    command: "server"
  mongo:
    image: mongo:6
    container_name: mongo
    restart: always
    ports:
      - "27017:27017"
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: password

Start Your Services

Bring up your Vault + MongoDB stack:

docker compose up -d

Step 2: Attach to the Vault Container

To interact with Vault CLI inside the container, run below command.

docker exec -it vault-dev /bin/sh

Now you’re inside the Vault container.

Step 3: Export the Vault Address

Before using Vault CLI, we need to tell it where Vault is running.

export VAULT_ADDR=http://localhost:8200

This command sets the Vault server address as an environment variable. The CLI uses this to send all your requests to Vault.

Step 4: Unseal the Vault

Vault is sealed by default for security. To unseal it, you need to provide at least three unseal key shares from the initialization step in Chapter 3.

Run the following command three times, each time providing one unseal key when prompted:

vault operator unseal

Paste a different unseal key each time. After the third key, Vault will be unsealed and ready to use.

Note: Use the unseal keys you saved during initialization. If those keys are lost, you'll need to reinitialize Vault from scratch.

Step 5: Login to Vault

Login as root

vault login <your-root-token>

(Replace <your-root-token> with your actual root token you have received when you performed the vault operator init.)

Step 6: Enable the Database Secrets Engine on the custom path

Now that you're connected to Vault, enable the database secrets engine on a custom path called mongo-db:

vault secrets enable -path=mongo-db database

We use a custom path to keep secrets engines organized. This way, multiple engines (e.g., MySQL, Postgres, MongoDB) won’t conflict.

Step 7: Configure MongoDB Connection

Set up the database configuration. Replace <USERNAME> and <PASSWORD> with environment variable references:

vault write mongo-db/config/main \
  plugin_name=mongodb-database-plugin \
  allowed_roles="readonly" \
  connection_url="mongodb://{{username}}:{{password}}@mongo:27017/admin?authSource=admin" \
  username="root" \
  password="password"

Explanation

  • plugin_name: Uses the official MongoDB plugin.
  • allowed_roles: Lists roles that are allowed to use this DB connection.
  • connection_url: Connection string using Vault's placeholders ({{username}}, {{password}}) that Vault injects dynamically.
  • username/password: MongoDB root credentials (set via environment).

Step 8: Create a Dynamic Role

Now define the dynamic role readonly:

vault write mongo-db/roles/readonly \
  db_name=main \
  creation_statements='{ "db": "admin", "roles": [ { "role": "readAnyDatabase", "db": "admin" } ] }' \
  default_ttl="1h" \
  max_ttl="24h"

What’s happening?

  • db_name=main: Tells Vault to use the DB config we defined earlier.
  • creation_statements: A MongoDB-specific JSON payload that defines what kind of user to create and what roles to assign.
  • default_ttl and max_ttl: Lifetime of the dynamic credentials.

The dynamic user will get a random username and password with readAnyDatabase privileges.

Step 9: Generate Dynamic Credentials

Let’s generate a set of dynamic credentials for the readonly role:

vault read mongo-db/creds/readonly

You’ll see that the new user has been dynamically created inside MongoDB, and will expire after 1 hour unless renewed.

Screenshot for “Step 9: Generate Dynamic Credentials” in chapter 17: Dynamic Secrets with MongoDB

Now let’s try to connect on the mongodb server using the newly dynamic secret.

Run below command which will connect us on the mongoDB server running inside our vault stack. Don’t forget to replace the <<username>> and <<password>> with the one you have received.

This command connects you to the MongoDB instance running inside our Vault stack using the temporary credentials Vault just generated.

You should see the successful login screen like below.

Screenshot for “Step 9: Generate Dynamic Credentials” in chapter 17: Dynamic Secrets with MongoDB

Want to Verify in Mongo Shell?

You can connect to the MongoDB as root user:

docker exec -it mongo mongosh -u root -p password --authenticationDatabase admin

Then run below command:

use admin
db.system.users.find()

Screenshot for “Want to Verify in Mongo Shell?” in chapter 17: Dynamic Secrets with MongoDB

You’ll see a user with a name like v-root-readonly-.... like below.

Optional: Revoke the Dynamic Secret

Run below command. Don’t forget to replace <<lease_id>> to the real id you have received from the step 9.

vault lease revoke <<lease_id>>

This will instantly disable the account.

Screenshot for “Optional: Revoke the Dynamic Secret” in chapter 17: Dynamic Secrets with MongoDB

Screenshot for “Optional: Revoke the Dynamic Secret” in chapter 17: Dynamic Secrets with MongoDB

You just learned how to configure dynamic secrets for MongoDB with Vault.