Illustration of a terminal

How to provision secrets as environment variables

Many applications that follow the popular 12-Factor App guidelines source their secrets from the environment. This guide will walk you through the steps necessary to achieve this with SecretHub.

Before you begin

Before you start, make sure you have completed the following steps:

  1. Install the SecretHub CLI for your OS.
  2. Sign up for a SecretHub account.

Step 1: Running the demo app

We will be using the SecretHub Demo app to demonstrate the process of injecting secrets as environment variables. This application serves a web page and tries to connect to using credentials provided in the environment (DEMO_USERNAME and DEMO_PASSWORD).

First, try to run the app locally without setting the username and password:

secrethub demo serve

A web page will now be served at http://localhost:8080, but if you visit it, you’ll see that it shows an error because it’s missing the username and password.

Step 2: Write your secrets

To get the demo application to work correctly, you’ll need to provide a username and password. You wouldn’t want to have those scattered around in plaintext, so let’s store those on SecretHub instead.

Here’s a nice shortcut to auto-generate the values for you at your-username/demo:

secrethub demo init

Step 3: Add the secrethub.env file

To provide a mapping between environment variables and secrets, create a file named secrethub.env in your project’s root directory, similar to this one:

DB_HOST = localhost
DB_USER = test-user
DB_PASS = {{ your-username/repo-name/password }}

The path {{ your-username/repo-name/password }} references the secret defined in the previous step.

Step 4: Passing the secrets to the application

Finally, to start an app with the secrets it needs automatically provisioned as environment variables, wrap it with the run command:

secrethub run -- secrethub demo serve

This command will set the environment variables as specified in the secrethub.env file and pass them to the subcommand. Moreover, it will also mask the secrets on stdout and stderr to avoid accidentally logging them.

If you visit http://localhost:8080 again, you’ll see that the red cross got replaced by a green checkmark. The wisdom that was hidden in the Demo API has now been revealed!

See also

Happy coding!