DEV Community

shyamajp
shyamajp

Posted on

Passing environment variables to GitHub Actions using dotenv

TL;DR - Create .env file using GitHub Secrets before running tests in your workflow file

Introduction

My backend project, written in TypeScript/Express, uses dotenv for environment variables. dotenv package takes variables in from .env file, but when I looked for a solution, everyone had env or with inside workflow file, which never worked for me. So I had to figure out something else.

Steps

  1. Add secrets to your repository
  2. Add a step to create .env file inside your workflow

Add secrets

  1. Go to repository's Settings page
    GitHub repository / Settings page

  2. Go to Secrets from the sidebar menu
    GitHub repository / Settings / Secrets

  3. Click New repository secret to add secrets
    Note that a secret cannot start with a prefix GITHUB_.

Add a step to create .env file in your GitHub workflow

Now that you have all secrets set up, you can access to them by ${{ secrets.YOUR_SECRET_NAME }}. Below is a working example workflow file.

/.github/workflows/test.yml

name: Run tests

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  build:
    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [14.x]

    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v2
        with:
          node-version: ${{ matrix.node-version }}
          cache: "npm"

      - name: Create .env file
        run: |
          touch .env
          echo MONGO_URI = ${{ secrets.MONGO_URI }} >> .env
          echo PORT = ${{ secrets.PORT }} >> .env
          echo BASE_URI = ${{ secrets.BASE_URI }} >> .env
          echo PASSPORT_GITHUB_CALLBACK_URL = ${{ secrets.PASSPORT_GITHUB_CALLBACK_URL }} >> .env
          echo PASSPORT_GITHUB_CLIENT_ID = ${{ secrets.PASSPORT_GITHUB_CLIENT_ID }} >> .env
          echo PASSPORT_GITHUB_CLIENT_SECRET = ${{ secrets.PASSPORT_GITHUB_CLIENT_SECRET }} >> .env
          echo SESSION_SECRET = ${{ secrets.SESSION_SECRET }} >> .env

      - name: Install dependencies
        run: npm ci

      - name: Build
        run: npm run build --if-present

      - name: Run tests
        run: npm test
Enter fullscreen mode Exit fullscreen mode

For explanation, I just renamed some steps from the template for more readability and added the Create .env file step with touch and echo. This will not commit .env to the repository nor publish your secrets. Your secrets will remain secret.

Conclusion

Basically adding a new step to create .env file before running tests will do the job, because that's how dotenv works.

Feel free to reach out if you have any questions or suggestions to make this article better. Thank you for reading. Happy Coding!

Top comments (0)