Inject secrets into config files

Secrets are often a small part of a bigger configuration file that is consumed on startup of an application.

For instance, your app could have an example.config file that looks something like this:

database:
    host: localhost
    port: 5432
    username: "<INSERT_USERNAME_HERE>"
    password: "<INSERT_PASSWORD_HERE>"

To avoid having your secrets spread throughout all of your config files, you can turn them into templates instead and let SecretHub inject the secrets into it on the fly.

To do this, you can use SecretHub’s injection syntax and replace the actual secrets throughout the file with the path of the secret:

database:
    host: localhost
    port: 5432
    username: "${ your-username/start/db_user:latest }"
    password: "${ your-username/start/db_password:latest }"

A secret path is recognized by placing it between ${ and } characters. Templates accept any number of ${ <path> } segments where <path> is the path to a secret version, defaulting to latest when no version is given.

Nothing is stopping you from combining multiple secrets into a single config value:

database:
    url: "postgresql://${ your-username/start/db_user:latest }:${ your-username/start/db_password:latest }@localhost:5432/postgres"

A common convention is to also add a .tpl suffix to the template: example.config.tpl.

Before you can inject the secrets into the template, make sure you add the db_user and db_password secrets to your repo:

echo "example_db_user" | secrethub write your-username/start/db_user
echo "example_password123" | secrethub write your-username/start/db_password

Now you can use the inject command to inject secrets on the fly and it will print out the injected template on stdout:

cat example.config.tpl | secrethub inject

There you go! You now have a config with the secrets injected that you can use to run your app:

database:
    host: localhost
    port: 5432
    username: "example_db_user"
    password: "example_password123"

As you can see, your config template is free of secrets. It can safely be checked into source control an shared with team members.

️️➡️ Next, let’s move on to passing secrets as environment variables to a process.