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

时间:2020-10-01 09:40:24

标签: 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

1 个答案:

答案 0 :(得分:1)

除非明确完成,否则在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中,并在构建期间生成。