Using dotenv (.env) files with Atlas
A .env
file is a simple text file used to store environment variables for applications. It helps developers manage
configuration settings, such as database credentials, API keys, and other sensitive information, without hardcoding them
into the source code. By using a .env
file, developers can keep their codebase clean, secure, and easily configurable
across different environments.
For developers who want to use .env
files with Atlas, there are two ways users can do so through the standard Atlas
HCL configuration file:
Write an HCL expression to load the file into Atlas
First, create a string
variable in your atlas.hcl
file that will contain the content of your .env
file.
Next, use a local expression to split the string and create a map of your .env
variable keys to their values.
Now, your .env
variables can be accessed by simply indexing this map with the name of your desired variable.
For example, let's say the URL to my database is defined in my .env
file, so I'd like to use that variable in my
atlas.hcl
file rather than having it written out in two different places.
# ... more variables
DATABASE_URL=mysql://localhost:3306/dev
# ... more variables
variable "envfile" {
type = string
default = "/path/to/.env"
}
locals {
envfile = {
for line in split("\n", file(var.envfile)): split("=", line)[0] => regex("=(.*)", line)[0]
if !startswith(line, "#") && length(split("=", line)) > 1
}
}
env {
name = atlas.env
url = local.envfile["DATABASE_URL"]
}
Since I've loaded my .env
variables into a local map, I can easily grab the URL to my database and apply it to env.url
.
Use an external program
If you have a .env
reader/parser of choice, you can also integrate that external program into atlas.hcl
so it can use its output.
Take the following implementation example:
data "external" "envfile" {
program = [
"npm",
"run",
"envfile.js"
]
}
locals {
envfile = jsondecode(data.external.envfile)
}
env "local" {
src = local.envfile.DATABASE_URL
}
First, we use npm run
to run a Javascript file envfile.js
that returns a string or JSON representation of the .env
file. Then, we use jsondecode
to read the JSON object or interpret the string as JSON to create a local object with the
.env
variables as its attributes. Finally, we can retrieve the values of the .env
variables by accessing them from
the envfile
object.
Have additional questions or feedback? Feel free to reach out on our Discord server.