如何在 bitbucket 管道上运行环境变量?

Hct*_*dez 5 yaml environment-variables reactjs bitbucket-pipelines

我已经了解了使用 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
Run Code Online (Sandbox Code Playgroud)

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

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

这是因为在我的 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"
  },
Run Code Online (Sandbox Code Playgroud)

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

我怎么能得到那个?

小智 2

迟到总比不到好...

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

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

base64 -w 0 .env > envout.txt
Run Code Online (Sandbox Code Playgroud)

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

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

echo $ENV_ENCODED | base64 -d > .env
Run Code Online (Sandbox Code Playgroud)

额外信息:

  1. 这需要一步完成,因此请将其包含在构建之前
  2. 如果未找到该命令,请使用带有 base64 的构建映像
  3. 其他选项是将 .env 包含在您托管在 AWS ECR 等安全服务上的 docker 映像中,并从那里提取映像,它将包含您的 .env 文件
  4. 如果有人能够将构建代理下载为工件,他们将能够查看您的 .env 的内容。这更像是一种威慑,而不是最安全的选择。
  5. 作为一个步骤添加- cat .env将验证该过程,但可能使用 fake .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
Run Code Online (Sandbox Code Playgroud)