Search code examples
yamlgithub-actionscicd

How to set an env secret in Github action?


I want to access env variables in my .env. But of course, we can't commit the .env file.

So I've added an action secret to my Github called MONGODB_PASSWORD. But when I tried to access that secret, it's not working as expected.

Any thought on how I can do this?

This is what I have in my .yml

name: Node.js CI

on:
  push:
    branches: ['master']
  pull_request:
    branches: ['master']

jobs:
  build:
    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [12.x, 14.x, 16.x]
        # See supported Node.js release schedule at https://nodejs.org/en/about/releases/

    steps:
      - uses: actions/checkout@v3
      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v3
        with:
          node-version: ${{ matrix.node-version }}
          cache: 'npm'
        env:
          MONGODB_PASSWORD: ${{ secrets.MONGODB_PASSWORD }} // Setting the secret here
      - run: npm ci
      - run: npm run build --if-present
      - run: npm run lint
      - run: npm run test
      - run: npm run test:e2e

Solution

  • Try setting env on job level instead of step level:

    name: Node.js CI
    
    on:
      push:
        branches: ['master']
      pull_request:
        branches: ['master']
    
    jobs:
      build:
        runs-on: ubuntu-latest
        env:
          MONGODB_PASSWORD: ${{ secrets.MONGODB_PASSWORD }} // Setting the secret here
    
        strategy:
          matrix:
            node-version: [12.x, 14.x, 16.x]
            # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
    
        steps:
          - uses: actions/checkout@v3
          - name: Use Node.js ${{ matrix.node-version }}
            uses: actions/setup-node@v3
            with:
              node-version: ${{ matrix.node-version }}
              cache: 'npm'
          - run: npm ci
          - run: npm run build --if-present
          - run: npm run lint
          - run: npm run test
          - run: npm run test:e2e