[Awesome Rust] Use dotenv, dotenv_codegen to loads environment variables from .env file

dotenv

This crate provides a configuration loader in the style of the ruby dotenv - https://github.com/bkeepers/dotenv gem. This library is meant to be used on development or testing environments in which setting environment variables is not practical. It loads environment variables from a .env file, if available, and mashes those with the actual environment variables provided by the operating system.

Prerequites

Cargo is the Rust package manager. Cargo downloads your Rust package’s dependencies, compiles your packages, makes distributable packages, and uploads them to crates.io - https://crates.io/, the Rust community’s package registry.

  • Install Rust and Cargo

The easiest way to get Cargo is to install the current stable release of Rust by using rustup. Installing Rust using rustup will also install cargo.

On Linux and macOS systems, this is done as follows:

1
$ curl https://sh.rustup.rs -sSf | sh

It will download a script, and start the installation. If everything goes well, you’ll see this appear:

1
Rust is installed now. Great!

Installation

Add it into the Cargo.toml:

1
2
3
4
5
6
7
# Cargo.toml

[dependencies]
# GitHub - dotenv-rs/dotenv: Library to help supply environment variables in testing and development
# https://github.com/dotenv-rs/dotenv
dotenv = "0.15.0"
dotenv_codegen = "0.15.0"

Usages

The easiest and most common usage consists on calling dotenv::dotenv when the application starts, which will load environment variables from a file named .env in the current directory or any of its parents; after that, you can just call the environment-related method you need as provided by std::os.

If you need finer control about the name of the file or its location, you can use the from_filename and from_path methods provided by the crate.

dotenv_codegen provides the dotenv! macro, which behaves identically to env!, but first tries to load a .env file at compile time.

Examples

A .env file looks like this:

1
2
3
4
5
# .env

# a comment, will be ignored
REDIS_ADDRESS=localhost:6379
MEANING_OF_LIFE=42

You can optionally prefix each line with the word export, which will conveniently allow you to source the whole file on your shell.

A sample project using Dotenv would look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
extern crate dotenv;

use dotenv::dotenv;
use std::env;

fn main() {
dotenv().ok();

// load from custom.env file.
// dotenv::from_filename("custom.env").ok();

// Loads the file at the specified absolute path.
// let my_path = env::home_dir().and_then(|a| Some(a.join("/.env"))).unwrap();
// dotenv::from_path(my_path.as_path()).ok();

for (key, value) in env::vars() {
println!("{}: {}", key, value);
}
}

Variable substitution

It’s possible to reuse variables in the .env file using $VARIABLE syntax. The syntax and rules are similar to bash ones, here’s the example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# .env

VAR=one
VAR_2=two

# Non-existing values are replaced with an empty string
RESULT=$NOPE #value: '' (empty string)

# All the letters after $ symbol are treated as the variable name to replace
RESULT=$VAR #value: 'one'

# Double quotes do not affect the substitution
RESULT="$VAR" #value: 'one'

# Different syntax, same result
RESULT=${VAR} #value: 'one'

# Curly braces are useful in cases when we need to use a variable with non-alphanumeric name
RESULT=$VAR_2 #value: 'one_2' since $ with no curly braces stops after first non-alphanumeric symbol
RESULT=${VAR_2} #value: 'two'

# The replacement can be escaped with either single quotes or a backslash:
RESULT='$VAR' #value: '$VAR'
RESULT=\$VAR #value: '$VAR'

# Environment variables are used in the substutution and always override the local variables
RESULT=$PATH #value: the contents of the $PATH environment variable
PATH="My local variable value"
RESULT=$PATH #value: the contents of the $PATH environment variable, even though the local variable is defined

Dotenv will parse the file, substituting the variables the way it’s described in the comments.

Using the dotenv! macro

Add dotenv_codegen to your dependencies, and add the following to the top of your crate:

1
2
#[macro_use]
extern crate dotenv_codegen;

Then, in your crate:

1
2
3
fn main() {
println!("{}", dotenv!("MEANING_OF_LIFE")); // Error: environment variable `MEANING_OF_LIFE` not defined
}

References

[1] GitHub - dotenv-rs/dotenv: Library to help supply environment variables in testing and development - https://github.com/dotenv-rs/dotenv

[2] dotenv - crates.io: Rust Package Registry - https://crates.io/crates/dotenv

[3] dotenv_codegen - crates.io: Rust Package Registry - https://crates.io/crates/dotenv_codegen

[4] GitHub - bkeepers/dotenv: A Ruby gem to load environment variables from .env. - https://github.com/bkeepers/dotenv