首页 > 解决方案 > 如何在 bitbucket 管道上运行环境变量?

问题描述

我已经了解了使用 bitbucket 的管道,我想制作一个新的管道来上传我的 react 应用程序(使用 create-react-app 引导)并上传到 Amazon S3 存储桶。

我做了一个bitbucket-pipelines.yml像这样的文件

image: node:10.15.3

pipelines:
  default:
    - step:
        name: Installing dependencies
        caches:
          - node
        script: # Modify the commands below to build your repository.
          - rm -rf package-lock.json
          - rm -f node_modules
          - yarn add
    - step:
        name: Build
        script:
          - yarn build

当 Bitbucket 运行它时,它会显示下一条错误消息

env-cmd -f .env.production.local react-scripts build
Error: Unable to locate env file at location (.env.production.local)

这是因为在我的 package.json 中,我使用 env-cmd 来读取构建脚本的环境变量。

  "scripts": {
    "start": "env-cmd -f .env.development.local react-scripts start",
    "build": "env-cmd -f .env.production.local react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

但我不知道如何在我的 bitbucket-pipelines.yml 文件中读取环境变量(本地化在我的 .env 文件中)

我怎么能得到那个?

标签: reactjsenvironment-variablesyamlbitbucket-pipelines

解决方案


迟到总比不到好...

.env、.env.production.local 或您想要的任何文件名。可互换。

首先对你的 .env 文件进行编码:

base64 -w 0 .env > envout.txt

然后将 envout.txt 的内容添加到 bitbucket $ENV_ENCODED 或类似的存储库变量中

将解码命令添加到您的管道:

echo $ENV_ENCODED | base64 -d > .env

额外信息:

  1. 这需要一步完成,所以在构建之前包含它
  2. 如果找不到该命令,请使用 base64 构建映像
  3. 其他选择是将 .env 包含在您托管在 AWS ECR 等安全服务上的 docker 映像中,然后从那里拉取映像,它将包含您的 .env 文件
  4. 如果有人能够下载构建代理作为工件,他们将能够查看您的 .env 的内容。这比最安全的选择更具威慑力。
  5. 作为一个步骤添加- cat .env将验证该过程,但可能使用假的 .env

我还建议您在同一步骤中进行安装和构建。我遇到了生成文件(尤其是 .env)在步骤之间不同的问题。

image: node:10.15.3

pipelines:
  default:
    - step:
        name: Installing dependencies and Build
        caches:
          - node
        script: # Modify the commands below to build your repository.
          - rm -rf package-lock.json
          - rm -f node_modules
          - yarn add
          - echo $ENV_ENCODED | base64 -d > .env
          - yarn build

推荐阅读