GitLab CI中Kaniko构建阶段无法获取dotenv传递的环境变量
GitLab CI中Kaniko构建无法获取dotenv变量的解决方法
问题场景
我在GitLab CI流水线里用Kaniko构建Docker镜像,由于Kaniko镜像本身不带Git工具,所以单独设置了一个prepare_docker阶段的任务,把当前Git哈希写入环境变量文件,通过dotenv制品传递给后续的构建阶段。
准备阶段配置:
prepare_docker_build_job: stage: prepare_docker extends: - .rules:new_push_pipelines <<: *before_script_template needs: [test_job] script: - echo "CUR_GIT_VERSION=$(git describe --always --dirty)" >> git_variables.env artifacts: reports: dotenv: git_variables.env
后续构建阶段配置:
docker_build_job: stage: docker_build needs: - job: prepare_docker_build_job optional: false artifacts: true extends: - .rules:new_push_pipelines image: name: gcr.io/kaniko-project/executor:debug entrypoint: [""] script: - echo "Current git version is $CUR_GIT_COMMIT" - echo "Current project path is $CI_PROJECT_DIR" - /kaniko/executor --context "$CI_PROJECT_DIR" --cache=true --dockerfile "${CI_PROJECT_DIR}/docker/docker_setup" --destination "${CI_REGISTRY_LOCATION}:${CI_COMMIT_TAG}" --build-arg CUR_GIT_COMMIT=$CUR_GIT_COMMIT
实际运行时,docker_build阶段的git_variables.env文件被删除,导致$CUR_GIT_COMMIT变量未定义。
解决步骤
1. 修正变量名不一致问题
这是最直接的错误:准备阶段写入的变量是CUR_GIT_VERSION,但构建阶段引用的是CUR_GIT_COMMIT,两者名称不匹配。需要统一变量名,比如修改准备阶段的脚本:
echo "CUR_GIT_COMMIT=$(git describe --always --dirty)" >> git_variables.env
2. 检查前置脚本是否清理文件
查看你引用的before_script_template中是否包含清理工作目录的命令(比如rm -rf *),如果有,需要排除git_variables.env避免被误删。例如修改前置脚本的清理步骤:
rm -rf !(git_variables.env)
3. 验证artifacts传递与变量导入
虽然needs中指定了artifacts: true,但可以:
- 检查全局/阶段级artifacts配置,是否有
exclude规则排除了git_variables.env - 在构建阶段开头添加验证命令,确认文件和变量状态:
# 查看文件是否存在 ls -la git_variables.env # 验证变量是否被导入环境 printenv | grep CUR_GIT_
4. 修正后的完整配置示例
准备阶段
prepare_docker_build_job: stage: prepare_docker extends: - .rules:new_push_pipelines <<: *before_script_template needs: [test_job] script: - echo "CUR_GIT_COMMIT=$(git describe --always --dirty)" >> git_variables.env artifacts: reports: dotenv: git_variables.env
构建阶段
docker_build_job: stage: docker_build needs: - job: prepare_docker_build_job optional: false artifacts: true extends: - .rules:new_push_pipelines image: name: gcr.io/kaniko-project/executor:debug entrypoint: [""] script: - # 先验证变量状态 - ls -la git_variables.env - printenv CUR_GIT_COMMIT - echo "Current git version is $CUR_GIT_COMMIT" - echo "Current project path is $CI_PROJECT_DIR" - /kaniko/executor --context "$CI_PROJECT_DIR" --cache=true --dockerfile "${CI_PROJECT_DIR}/docker/docker_setup" --destination "${CI_REGISTRY_LOCATION}:${CI_COMMIT_TAG}" --build-arg CUR_GIT_COMMIT=$CUR_GIT_COMMIT
内容的提问来源于stack exchange,提问作者arc_lupus
相关产品推荐
相关产品推荐

