【问题标题】:Can I pass environment variables from Gitlab .gitlab-ci.yml to a React app?我可以将环境变量从 Gitlab .gitlab-ci.yml 传递到 React 应用程序吗?
【发布时间】:2020-03-12 10:38:07
【问题描述】:

我正在尝试使用 gitlab CI 管道动态设置环境变量。 我想要实现的是根据我部署到的阶段(阶段、产品)注入正确的 API 密钥和 URL。

在我的 React 应用程序中,我使用 process.env.REACT_APP_APPSYNC_URL 访问变量,如 react documentation 中所述。

到目前为止,我已经尝试在gitlab UI 中设置变量并在我的.gitlab-ci.yml 文件中引用它们(参见下面的代码)。

很遗憾,我无法通过这种方式访问​​变量,因此我将非常感谢您的帮助。

我刚刚开始使用 CI/CD 和不同的环境,所以如果我在这里通常使用不好的方法,请告诉我!

这是 .gitlab-ci.yml:

image: nikolaik/python-nodejs:latest

stages:
  - install
  - test
  - deploy

install:
  stage: install
  script:
    - npm install
    - npm run build
  artifacts:
    untracked: true
  only:
    - stage
    - master

test:
  stage: test
  dependencies:
    - install
  script:
    - npm run test
  artifacts:
    untracked: true
  only:
    - stage
    - master

deployDev:
  stage: deploy
  only:
    - stage
  dependencies:
    - install
    - test
  script:
    - pip3 install awscli
    - aws configure set aws_access_key_id "$DEV_AWS_KEY"
    - aws configure set aws_secret_access_key "$DEV_AWS_SECRET"
    - aws s3 sync ./build/ s3://example.dev
  variables:
    REACT_APP_COGNITO_REGION: $DEV_COGNITO_REGION
    REACT_APP_COGNITO_USER_POOL_ID: $DEV_COGNITO_USER_POOL_ID
    REACT_APP_COGNITO_APP_CLIENT_ID: $DEV_COGNITO_APP_CLIENT_ID
    REACT_APP_COGNITO_IDENTITY_POOL_ID: $DEV_COGNITO_IDENTITY_POOL_ID
    REACT_APP_APPSYNC_URL: $DEV_APPSYNC_URL
    REACT_APP_APPSYNC_REGION: $DEV_APPSYNC_REGION
    REACT_APP_APPSYNC_AUTHENTIACTION_TYPE: $DEV_APPSYNC_AUTHENTIACTION_TYPE
deployProd:
  stage: deploy
  only:
    - master
  dependencies:
    - install
    - test
  script:
    - pip3 install awscli
    - aws configure set aws_access_key_id "$PROD_AWS_KEY"
    - aws configure set aws_secret_access_key "$PROD_AWS_SECRET"
    - aws s3 sync ./build/ s3://example.com

干杯!

【问题讨论】:

  • 您也可以在 UI 中直接创建具有正确名称(即REACT_APP_APPSYNC_REGION)的变量,但为您的不同environment 使用不同的范围
  • 这个文件的问题是没有build stage。。把install和build分开,然后把variables部分移到build stage

标签: reactjs environment-variables gitlab gitlab-ci


【解决方案1】:

CRA docs 中的这一行很重要:环境变量是在构建期间嵌入的。 所以在运行构建命令之前设置变量。

image: node:10.16.0-alpine

stages:
  - build
  - deploy

build_app:
  stage: build
  script:
    - export REACT_APP_SECRET_API_KEY=$API_KEY # set REACT_APP variables before build command
    - yarn install
    - yarn build
  artifacts:
    name: "$CI_PIPELINE_ID"
    paths:
      - build
    when: on_success

deploy_app:
  stage: deploy
  dependencies:
    - build_app
  script:
    - echo "Set deployment variables"
    - echo "Deployment scripts"

【讨论】:

  • 使用 gitlab ci 的 variables 功能很好,但它只是不在正确的阶段。为清楚起见,首选variables 而不是script/export
猜你喜欢
  • 2021-01-28
  • 2023-02-24
  • 1970-01-01
  • 1970-01-01
  • 2020-02-14
  • 1970-01-01
  • 1970-01-01
  • 2021-07-25
  • 2021-04-17
相关资源
最近更新 更多