Ruby

Use Dotenvx with Ruby.

Install

Get the Dotenvx Ruby gem.

$ gem install dotenvx

And the CLI to encrypt files:

$ curl -sfS https://dotenvx.sh | sh

Encrypt

Start with a secret value in your .env file, like:

# .env
HELLO="Secret"

Encrypt it with a single command.

$ dotenvx encrypt
◈ encrypted (.env)

The values become ciphertext and only your private key can unlock them.

# .env
DOTENV_PUBLIC_KEY="0220d830351410598be484f43a7b07097e09851f50426832876e8b5815a1752990"

HELLO="encrypted:BHLTACNJMr00nTG6yXpkCyWFKF/MY0ajN855tg3uVtKopTe2AGzSkQlcPd21pTOT3Ci8IKrdIg2TMZFoq1mDR6yb06QCRvqHXtpkZkAHYCEHfeWqqC8tMFovcYq5JS2uZSrC/qUGDA=="

Commit

Commit your encrypted .env files with your code. It's safe. Now you can securely share secrets through git.

$ git add .env
$ git commit -m "encrypt .env"

Ship

Load your secrets before your app uses them. Create an app.rb file:

# app.rb
require "dotenvx"

Dotenvx.load

puts "Hello #{ENV['HELLO']}"

Run your app:

$ ruby app.rb
⟐ injected env (2) from .env
Hello Secret

Dotenvx uses your private key to decrypt and inject your secrets just-in-time to your code.

Deploy

Find your private key with the keypair command.

$ dotenvx keypair
{"DOTENV_PUBLIC_KEY":"0220d830351410598be484f43a7b07097e09851f50426832876e8b5815a1752990","DOTENV_PRIVATE_KEY":"b37dbad0e00206f31486c4f44f8cc7abf2f1be96d5ba352eb791122b5e131bbf"}

Deploy your code and encrypted .env file, install your gems, and set DOTENV_PRIVATE_KEY on your production environment. Keep .env.keys on your local machine.

And run your app:

$ ruby app.rb
⟐ injected env (2) from .env
Hello Secret

Dotenvx uses your private key to decrypt and inject your secrets just-in-time, but this time with the private key stored on your server.

Production

Give production its own secrets by creating a .env.production file:

# .env.production
HELLO="Production"

Encrypt it:

$ dotenvx encrypt -f .env.production
◈ encrypted (.env.production)

Commit it:

$ git add .env.production
$ git commit -m "encrypt .env.production"

Find the matching private key with dotenvx keypair -f .env.production. Set it as DOTENV_PRIVATE_KEY and set DOTENV_FILE to .env.production on your server.

Tell the Ruby gem to load .env.production:

# app.rb
require "dotenvx"

Dotenvx.load(".env.production")

puts "Hello #{ENV['HELLO']}"

Run it:

$ ruby app.rb
⟐ injected env (2) from .env.production
Hello Production

Dotenvx loads .env.production and uses DOTENV_PRIVATE_KEY to unlock it. Your app reads its production secrets through ENV.

You can also load multiple files with Dotenvx.load(".env.production", ".env"). The first value wins. Make each file's matching private key available.

Conclusion

You've encrypted a .env file, committed it to git, and loaded its secrets with the Ruby gem. You've also learned how to set a private key on your server and choose a separate encrypted file for production.

Your secrets now travel with your code, and each environment needs just one private key to use them.