Use dotenvx with GitHub Actions

Use dotenvx with GitHub Actions

Initial setup

Create a Hello World build file. It's a very simple build script but yours could be more complicated - like a test suite or something.

// build.js
console.log(`Hello ${process.env.HELLO || ''}`)

Create a .github/workflows/ci.yml file.

# node
name: build
on: [push]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    - uses: actions/setup-node@v3
      with:
        node-version: 16
    - run: node build.js
      env:
        DOTENV_KEY: ${{ secrets.DOTENV_KEY }}

Commit that to code and push to GitHub.

github actions build

The build will say Hello [blank] as it doesn't have a way to access the environment variable yet. Let's do that next.

Install dotenvx

Install dotenvx to your .github/workflows/ci.yml file.

name: build
on: [push]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    - uses: actions/setup-node@v3
      with:
        node-version: 16
    - run: curl -fsS https://dotenvx.sh/ | sh
    - run: dotenvx run -- node build.js
      env:
        DOTENV_KEY: ${{ secrets.DOTENV_KEY }}
github actions build

The logs tell us missing .env file. This is expected, as we don't want to commit .env to code. It also tells us, for ci, that we should set DOTENV_KEY. That is what we want to do. Let's do that next by first adding our .env.ci environment.

Add ci environment

Create a .env.ci file in the root of your project.

# .env.ci
HELLO="ci/cd"

Encrypt secrets

Use dotenvx to encrypt your secrets.

dotenvx encrypt

This generates a .env.vault and .env.keys file.

.env.vault

#/-------------------.env.vault---------------------/
#/         cloud-agnostic vaulting standard         /
#/   [how it works](https://dotenv.org/env-vault)   /
#/--------------------------------------------------/

# ci
DOTENV_VAULT_CI="Fzz16lWV2m2m15DEhsMKSQUtPDYceiUGI+1xAUjZ+FpXde0h9fWM/jlITUR7mll9BwVzag=="

The .env.vault file contains encrypted (AES-256-GCM) versions of your secrets, and the .env.keys file contains the decryption keys.

.env.keys

#/!!!!!!!!!!!!!!!!!!!.env.keys!!!!!!!!!!!!!!!!!!!!!!/
#/   DOTENV_KEYs. DO NOT commit to source control   /
#/   [how it works](https://dotenv.org/env-keys)    /
#/--------------------------------------------------/
DOTENV_KEY_CI="dotenv://:key_a78ddf83e06fc4cfd357f7ebb68bc59f20a64b5b6bc607c82e16635df26cf9bf@dotenvx.com/vault/.env.vault?environment=ci"

We're ready to set DOTENV_KEY on GitHub actions.

Set DOTENV_KEY

Set DOTENV_KEY on GitHub Actions using the ci key in your .env.keys file.

www.github.com

Build CI

Commit those changes safely to code and rerun the build.

That's it! On rerun, your .env.vault file will be decrypted and its CI secrets injected as environment variables – just in time. Your build script will say Hello ci/cd.

You'll know things worked correctly when you see injecting env (1) from encrypted .env.vault in your logs.

github actions build