将环境变量传递给 CircleCI 中的 node.js 进程

pass environment variable to node.js process in CircleCI

我正在通过使用 CircleCI 上下文(项目设置 -> 环境变量。

在 CircleCI config.yml 中获取环境变量

我无法将它们传递给 node.js 进程 process.env.SERVER_API。他们是 undefined.

我试着让他们把它传给 config.yml:

docker:
      - image: circleci/node:14.9.0
        environment:
          SERVER_API: $SERVER_API

不行,不知道怎么传。

config.yml

version: 2.1
executors:
  node-executor:
    docker:
      - image: circleci/node:14.9.0
        environment:
          SERVER_API: $SERVER_API
commands:
  gatsby-build:
    steps:
      - checkout
      - restore_cache:
          keys:
            - yarn-cache-{{ checksum "yarn.lock" }}
      - run:
          name: Install Dependencies
          command: yarn install
      - save_cache:
          key: yarn-cache-{{ checksum "yarn.lock" }}
          paths:
            - ./node_modules
      - run:
          name: Gatsby Build
          command: yarn build
workflows:
  version: 2
  build-deploy:
    jobs:
      - release:
          filters:
            branches:
              only:
                - master
jobs:
  release:
    executor: node-executor
    working_directory: ~/tau-guide-website
    steps:
      - gatsby-build
      - run:
          name: Deploy
          command: |
            #upload all the code to machine
            scp -r -o StrictHostKeyChecking=no ~/tau-guide-website/public $PROJECT_FOLDER

在 Circle CI 构建期间出现的环境变量不会传递给部署的代码,除非明确指定。 对于我的项目,我为管道使用可用的 Circle CI env 变量,但将它们导出到 .env 文件以将它们包含在最终包中。对于当前代码,我会:

从图片中删除:

environment: SERVER_API: $SERVER_API

在构建步骤中添加额外的代码:

      - run:
          name: Gatsby Build
          command: |
            touch .env.production
            echo "SERVER_API=$SERVER_API" > .env.production
            yarn build

如果根本不使用 .env,请考虑阅读 dotenv package。您需要引入 dotenv 作为依赖项并在您的文件中声明它,如下所示:

require('dotenv').config({
  path: `.env.${process.env.NODE_ENV}`,
})

对于我们的用例,.env 也包含数据库凭据和机密,但在 .gitignore 中并在构建期间生成。