Hashicorp Vault 101: Dynamic MYSQL Credentials using Vault

Chris Edward Rego
2 min readMar 13, 2021

Hashicorp Vault 101 is a series of straightforward guides to go down the rabbit hole with Vault. In this guide, we would understand what it takes to create dynamic MySQL credentials using Hashicorp Vault.

What is Vault?

Vault as the name suggests is a secret management tool from Hashicorp that allows managing storing secrets such as username, password, database credentials.

Setting up: Vault + MYSQL in 2mins.

For the purpose of this guide, we will use Docker Compose to spin-off vault & MySQL containers, with a couple of configuration settings.

Download or copy this file in a specific folder

https://gist.githubusercontent.com/chrisedrego/654e6177fc2a7e2d0278306d83ff3f14/raw/4db06baa1c3076ad7520bf3bb753e5f2fd0194d6/vault-mysql-docker-compose.yaml

Navigate to the folder and run.

docker-compose up
Hashicorp Vault + MYSQL ❤ Ready!

Creating a separate user for Vault in MYSQL

Although we can use root credentials in Vault to authenticate to MYSQL, it's recommended best practice to create a separate user in MYSQL for vault which will have all required privileges. In this case, we will exec into the MYSQL container and create a user called as vault.

# Connecting to MYSQL
docker exec -it mysql-dev mysql -uroot -p'root'
CREATE USER 'vault'@'%' IDENTIFIED BY 'vault';
GRANT ALL PRIVILEGES ON *.* TO 'spring' WITH GRANT OPTION;

Setting up Configuration in Vault to create Dynamic user.


# Connecting to Vault container
docker exec -it vault-dev sh
# Setting the VAULT_TOKEN & VAULT_ADDR for authentication
export VAULT_TOKEN=00000000–0000–0000–0000–000000000000
export VAULT_ADDR=http://127.0.0.1:8200
# Enable Generic Database
vault secrets enable database
# Configure Database for MYSQL configuration
vault write database/config/mysql-db \
plugin_name=mysql-database-plugin \
connection_url='spring:spring@tcp(mysql-dev:3306)/' \ allowed_roles="*" \
username='spring' \
password='spring' \
default_ttl="1h" \
max_ttl="386h"

# Configure Roles to create Dynamic users
vault write database/roles/mysql-db-role db_name=mysql-db creation_statements="CREATE USER '{{name}}'@'%' IDENTIFIED BY '{{password}}';GRANT SELECT ON *.* TO '{{name}}'@'%';" default_ttl="1h" max_ttl="386h"

# Executing the role to create Dynamic User
vault read mysql/creds/mysql-db-role

BOOM! We are done.

“if you found this article useful, feel free to 👏 clap many times or share it with your friends. Also follow me for more DevSecOps content”

--

--

Chris Edward Rego

Lead DevSecOps. Talks about Cloud Architecture, DevOps & SRE. For more info check https://www.linkedin.com/in/chrisedrego/