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

GitLab CI/CD执行Terraform apply时引用子模块报错:master分支不存在

问题

我通过以下方式引用Terraform模块:

source =  "git::https://gitlab.com/dash-infrastructure.git//modules/lambda-apigw-api"

在GitLab CI/CD中,terraform plan执行正常,但在terraform apply阶段出现如下错误:

│ Error: Failed to download module
│ 
│   on main-lambda-apigw-from-module.tf line 1:
│    1: module "lambda_apigw_module" {
│ 
│ Could not download module "lambda_apigw_module"
│ (main-lambda-apigw-from-module.tf:1) source code from
│ "git::https://gitlab.com/dash-infrastructure.git":
│ error downloading
│ 'https://gitlab.com/dash-infrastructure.git':
│ /usr/bin/git exited with 1: error: pathspec 'master' did not match any
│ file(s) known to git

该模块仓库中根本不存在master分支,我尝试指定默认分支main或提交哈希:

source =  "git::https://gitlab.com/dash-infrastructure.git//modules/lambda-apigw-api/?ref=main"

但问题依旧存在,请问问题出在哪里?

原因分析
  • Terraform模块缓存差异:terraform plan执行时已下载模块并缓存,但CI/CD环境中apply阶段可能未复用缓存,重新拉取时Terraform默认尝试拉取master分支,与仓库实际默认分支main冲突。
  • Git源格式错误:你把?ref=main放在了模块路径之后,不符合Terraform的Git源引用规则,导致参数未被识别。
  • CI环境Git配置干扰:部分CI环境的Git配置可能强制默认分支为master,忽略了URL中的ref参数。
解决方案
  • 修正模块源URL格式:将ref参数紧跟在仓库URL末尾,再用//分隔模块路径,正确写法如下:
    source = "git::https://gitlab.com/dash-infrastructure.git?ref=main//modules/lambda-apigw-api"
    
  • 强制重新初始化模块:在CI/CD的apply阶段执行terraform init -upgrade,清理旧缓存并拉取指定分支的模块。
  • 统一CI环境Git配置:在CI脚本中添加git config --global init.defaultBranch main,避免环境默认分支设置干扰。

内容的提问来源于stack exchange,提问作者milieere

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 03:40:05