How to set environment variable in node.js process when deploying with github action

混江龙づ霸主 提交于 2020-07-19 11:18:08

问题


I am trying to build an CI pipeline for my node.js server using github actions.

I just need to solve one issue. I need to set environment variable, so that my node.js server can access the env variable via process.env

Below is the github action workflow file.

name: Build and Deploy to GKE

on:
  pull_request:
    branches:
      - master

# Environment variables available to all jobs and steps in this workflow
env:
  ENGINE_API_KEY: ${{ secrets.ENGINE_API_KEY }}

jobs:
  setup-build-publish-deploy:
    name: Setup, Build, Publish, and Deploy
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - name: Apollo Schema Update
        env:
          ENGINE_API_KEY: ${{ secrets.ENGINE_API_KEY }}
        run: |
          sudo npm install
          sudo npm install -g apollo
          sudo npm run dev &
          sleep 3
          sudo apollo service:push --serviceURL=http://auth-cluster-ip-service --serviceName=auth --tag=master --endpoint=http://localhost:3051

I have tried declaring environment variable both workflow level and job's level, but when I console.log(process.env.ENGINE_API_KEY), it returns undefined.

I also tried ENGINE_API_KEY=$ENGINE_API_KEY npm run dev & instead of npm run dev &. This works on my macbook, but with github action, it still returns undefined.

(I did store ENGINE_API_KEY in settings -> secret. worked fine for other variables)


回答1:


Create an .env file that can be read by your node server and pass in your repository secret that way. This should be done after your checkout step:

    - name: create env file
      run: |
        touch .env
        echo ENGINE_API_KEY =${{ secrets.ENGINE_API_KEY }} >> .env



回答2:


kachow6 answer is right but you must add the created file into the git repository, and if you have a .gitignore file present, that ignore the .env file, you must edit/delete it. So your jobs must be like:

- name: Checkout the repository
  uses: actions/checkout@v2

- name: Create .env file
  run: |
    touch .env
    echo SECRET=${{ secrets.SECRET }} >> .env

- name: Delete gitignore
  run: |
    rm .gitignore

- name: Push .env to directory
  run: |
    git config user.email "EMAIL"
    git config user.name "USERNAME"
    git add .
    git commit -m "environment variables"

some useful resource used: https://github.community/t/can-github-actions-directly-edit-files-in-a-repository/17884/2



来源:https://stackoverflow.com/questions/61117865/how-to-set-environment-variable-in-node-js-process-when-deploying-with-github-ac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!