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

Gitlab Pipeline无法访问Gitlab源的Terraform模块

Terraform模块拉取失败解决指南

问题详情

  • Repo A:用于创建EC2的Terraform配置文件(运行正常)
  • Repo 2中的配置代码:
module "my-ec2-instances" {
    source = "git::https://gitlab.com/myawsmodules/my-ec2?ref=main"
    project_name = "module-test"
    env_name = "test"
}
  • 已将模块仓库添加至GitLab项目的允许项目列表(路径:Settings->CI/CD->Token Access)
  • Pipeline运行时触发错误:

Error: Failed to download module
│
│ on main.tf line 1:
│ 1: module "my-ec2-instances" {
│
│ Could not download module "my-ec2-instances" (main.tf:1) source code from
│ "git::https://gitlab.com/myawsmodules/my-ec2": error downloading
│ 'https://gitlab.com/myawsmodules/my-ec2': /usr/bin/git exited with 128:
│ Cloning into '.terraform/modules/my-ec2-instances'...
│ fatal: could not read Username for 'https://gitlab.com': No such device or
│ address

可行解决步骤

1. 配置CI/CD认证变量

  • 到模块仓库(gitlab.com/myawsmodules/my-ec2)的Settings->Access Tokens页面,创建一个项目访问令牌,勾选read_repository权限,记录令牌值和默认用户名gitlab-ci-token
  • 在Repo 2的Settings->CI/CD->Variables中添加两个变量:
    • GITLAB_USERNAME:值填gitlab-ci-token
    • GITLAB_TOKEN:值填创建的项目访问令牌,勾选保护和掩码选项

2. 调整模块源地址或预配置Git凭证

方式一:修改Terraform模块源

把模块的source地址改成带认证的格式,让Terraform拉取时自动带上凭证:

module "my-ec2-instances" {
    source = "git::https://${var.GITLAB_USERNAME}:${var.GITLAB_TOKEN}@gitlab.com/myawsmodules/my-ec2?ref=main"
    project_name = "module-test"
    env_name = "test"
}

注:需在Terraform变量中声明GITLAB_USERNAME和GITLAB_TOKEN,或直接引用CI环境变量。

方式二:在CI脚本中配置Git凭证

在Pipeline的before_script里添加Git凭证配置,让后续的terraform init自动完成认证:

before_script:
  - git config --global credential.helper store
  - echo "https://${GITLAB_USERNAME}:${GITLAB_TOKEN}@gitlab.com" > ~/.git-credentials

3. 检查仓库权限与网络

  • 确认添加到允许项目列表的模块仓库路径完全正确,无拼写错误
  • 排查CI Runner是否能正常访问GitLab.com,排除代理、防火墙等网络限制

4. 改用GitLab模块注册表(推荐)

如果模块仓库已发布到GitLab模块注册表,直接使用注册表地址,CI会自动用项目令牌完成认证,无需手动配置凭证:

module "my-ec2-instances" {
    source = "gitlab.com/myawsmodules/my-ec2/my-ec2-instances"
    version = "1.0.0" # 替换为模块实际版本号
    project_name = "module-test"
    env_name = "test"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 02:30:22