You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GitLab CI/CD中dotenv文件无法传递至后续阶段的问题

GitLab CI/CD中dotenv变量无法传递到后续作业的问题

我有一个包含5个阶段的大型CI/CD流水线,在第一个build阶段创建了dotenv文件,希望在后续部分阶段中使用。按照官方文档配置后,始终无法将dotenv文件传递至其他作业/阶段。

以下是gitlab-ci.yml的相关片段:

stages:
  - build
  - create-image
  - post-image-creation
  # 为简洁起见省略其余阶段

image: alpine:3.14.3

setup-dotenv-file:
  stage: build
  artifacts:
    reports:
      dotenv: build.env
  script:
    - echo "Setting up build.env file"
    - echo "On branch $CI_COMMIT_REF_NAME"
    - |
      if [[ "$CI_COMMIT_REF_NAME" == "test" ]]; then
        cat $TEST_ENV_FILE > build.env && source build.env
      elif [[ "$CI_COMMIT_REF_NAME" == "stage" ]]; then
        cat $STAGE_ENV_FILE > build.env && source build.env
      elif [[ "$CI_COMMIT_REF_NAME" == "master" ]]; then
        cat $PROD_ENV_FILE > build.env && source build.env
      else
        echo "No environment file found for this branch."
      fi
    - ls -la
  only:
    - test
    - stage
    - master

# 为简洁起见省略创建镜像的作业

post-template-lab:
  stage: post-image-creation
  image: mcr.microsoft.com/powershell:lts-7.2-alpine-3.14
  variables: 
    ErrorActionPreference: stop
  tags:
    - pwsh
  script:
    - cd General/Scripts
    - .\post-template.ps1 -paramter1 $VARIABLE_FROM_DOTENVFILE -paramter2 $VARIABLE_FROM_DOTENVFILE
  retry: 2
  needs:
    - setup-dotenv-file
    - # 来自create-image阶段的多个作业
  only:
    - test

运行流水线时,可以看到build.env文件已创建并上传:

Uploading artifacts...
build.env: found 1 matching artifact files and directories 
Uploading artifacts as "dotenv" to coordinator... 201 Created  id=7527 responseStatus=201 Created token=xxxxxxx
Cleaning up project directory and file based variables

但在Web界面中无法看到该文件:
Web界面中工件概览为空

并且当post-template-lab作业运行时,收到变量未定义的错误。

尝试过使用dependencies:和needs:的不同配置,但都无效。猜测可能是因为使用了不同的镜像/脚本语言,需要在后续阶段的PowerShell中重新加载dotenv文件,但目前无法实现,因为文件并未传递到该作业中:

$ ls -la # post-template-lab作业中的执行结果
22total 52
23drwxr-xr-x    9 root     root          4096 Sep 15 08:23 .
24drwxr-xr-x    4 root     root          4096 Aug 29 15:26 ..
25-rw-r--r--    1 root     root           745 Sep 15 08:23 .env.sample
26drwxr-xr-x    6 root     root          4096 Sep 15 09:52 .git
27-rw-r--r--    1 root     root           703 Sep 15 08:23 .gitignore
28-rw-r--r--    1 root     root          1608 Sep 15 08:23 .gitlab-ci.yml
[...]

内容的提问来源于stack exchange,提问作者Jonas Hüsser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 16:34:50