direnv can be integrated into GitHub Actions workflows to manage environment variables from .envrc
files. This is particularly useful for:
.envrc
files in your CI pipelineThe direnv export gha
command outputs environment variables in the format required by GitHub Actions. Here’s a basic example:
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install direnv
run: |
curl -sfL https://direnv.net/install.sh | bash
echo "$HOME/.local/bin" >> $GITHUB_PATH
- name: Load environment variables
run: |
direnv allow .
direnv export gha > "$GITHUB_ENV"
- name: Run tests
run: |
# Your environment variables from .envrc are now available
echo "DATABASE_URL=$DATABASE_URL"
make test
There are several ways to install direnv in your GitHub Actions workflow:
- name: Install direnv
run: |
curl -sfL https://direnv.net/install.sh | bash
echo "$HOME/.local/bin" >> $GITHUB_PATH
On Ubuntu runners:
- name: Install direnv
run: sudo apt-get update && sudo apt-get install -y direnv
On macOS runners:
- name: Install direnv
run: brew install direnv
- name: Install direnv
run: |
wget -O direnv https://github.com/direnv/direnv/releases/download/v2.34.0/direnv.linux-amd64
chmod +x direnv
sudo mv direnv /usr/local/bin/
direnv allow
: Even in CI, direnv requires explicit permission to load .envrc
filesMake sure you’re using > "$GITHUB_ENV"
to override to the GitHub environment file:
# Correct
direnv export gha > "$GITHUB_ENV"
# Incorrect - this just prints to stdout
direnv export gha
Ensure direnv is executable and in your PATH:
- name: Install and setup direnv
run: |
curl -sfL https://direnv.net/install.sh | bash
echo "$HOME/.local/bin" >> $GITHUB_PATH
# Force PATH update in current step
export PATH="$HOME/.local/bin:$PATH"
direnv allow .
direnv export gha >> "$GITHUB_ENV"
To debug issues, you can examine what direnv is doing:
- name: Debug direnv
run: |
direnv version
direnv status
cat .envrc
direnv allow .
direnv export gha
Here’s a complete example for a Node.js project:
name: Node.js CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18.x, 20.x]
steps:
- uses: actions/checkout@v4
- name: Install direnv
run: |
curl -sfL https://direnv.net/install.sh | bash
echo "$HOME/.local/bin" >> $GITHUB_PATH
- name: Setup Node.js $
uses: actions/setup-node@v4
with:
node-version: $
- name: Load environment
run: |
# Create .envrc if it doesn't exist
if [ ! -f .envrc ]; then
cat > .envrc <<'EOF'
export NODE_ENV=test
export DATABASE_URL="postgresql://localhost/test_db"
PATH_add node_modules/.bin
EOF
fi
direnv allow .
direnv export gha >> "$GITHUB_ENV"
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Run linter
run: npm run lint