Auto-generate .env-example files
To manage these environment variables, a common approach is to use a .env
file to store the actual values. However, to make sure others who work on the project know the required environment variables and their intended values, it's standard practice to provide a .env-example
file. Such files list the secret names and example values so that others can quickly get up and running.
Creating a .env-example
file usually requires developers to manually list all of their secrets, along with default values and helpful comments, which can become time-consuming and repetitive. Every time a new secret is added, the process must be repeated. In this article, we'll explore how this process can be streamlined.
High-level overview
To automate the creation of the .env-example
file, we'll use a secrets manager named Infisical. Infisical provides a web UI for managing secrets and a CLI tool for injecting them into development, staging, and production environments. The focus of this article will be on the CLI tool's ability to generate the .env-example
.
Walkthrough
In the Infisical dashboard, you can add secrets along with their associated tags and comments. Comments are useful when we want to provide additional information about a secret. In comments, we can also define a default value to be used when generating the .env-example
file by adding DEFAULT:<some value>
. We can see that for the secret named MONGO_DB
above, we have set a default value to be used in the example .env.
The tags placed on secrets help to group related secrets together. This will allow the generator to group our secrets which belong to common tags.
Generating the example .env file
If you haven’t installed the Infisical CLI, you will need to do so by following the instructions here. Once the CLI has been installed, you will have to connect the Infisical project to your local project with the command infisical init
.
After connecting your local project to an Infisical project, run the following command to generate the .env-example
file.
infisical secrets generate-example-env > .example-env
This will output a file named `.example-env` in the current working directly. The example output is shown below.
In the output file above, we can see that secrets that are tagged with a common tag are grouped together. For each secret under a group, comments are placed above the secret. If a comment in Infisical has syntax in the format of DEFAULT:<value>
then the value will be extracted and used as the default value for the given secret.
To learn more about all the available commands, visit https://infisical.com/docs/getting-started/introduction