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

GitLab Runner克隆同实例私有子模块:SSH密钥需求与配置

GitLab CI中子模块非相对路径的认证配置方案

我在使用GitLab时,即便子模块和主仓库在同一实例里,也习惯避免用相对路径——相对路径容易出错、查找费时间,分叉时还可能出问题。我的主仓库引用了同GitLab实例、同组但路径稍有不同的私有子模块,原本注册的组Runner能正常构建所有项目,但加了子模块后克隆失败:

  • SSH方式报错:
Host key verification failed.
fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.
  • HTTPS方式报错:
remote: The project you were looking for could not be found or you don't have permission to view it.
fatal: repository 'https://gitlab.example.de/user/example/example-group/project-development-setup.git/' not found

本地执行submodule init要配置SSH密钥,但没想到同一组的CI作业克隆子模块也需要密钥。不想用相对URI的话,可通过以下几种方式结合GitLab CI变量完成认证:

方法1:用CI_JOB_TOKEN做HTTPS认证(推荐)

GitLab CI内置的CI_JOB_TOKEN可直接用于同实例内仓库的认证,无需额外密钥。配合GIT_SUBMODULE_STRATEGY变量,步骤如下:

  1. 在.gitlab-ci.yml中配置变量和预处理脚本:
variables:
  GIT_SUBMODULE_STRATEGY: recursive
  # 可选:只克隆指定子模块路径,节省时间
  # GIT_SUBMODULE_PATHS: "path/to/your/submodule"

before_script:
  # 替换子模块的HTTPS地址,注入CI_JOB_TOKEN
  - git config --file .gitmodules submodule.<你的子模块名>.url https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.example.de/user/example/example-group/project-development-setup.git
  # 同步子模块配置并更新
  - git submodule sync
  - git submodule update --init --recursive

注意:<你的子模块名>可通过本地执行git submodule status查看。

方法2:SSH密钥配合CI变量

如果坚持用SSH方式,需要注入有权限访问子模块的密钥:

  1. 生成一对SSH密钥,把公钥添加到子模块仓库的部署密钥中(给只读权限即可)。
  2. 将私钥作为CI/CD变量(比如命名为SSH_PRIVATE_KEY)添加到主仓库或组的CI设置里,勾选「保护变量」和「掩码变量」。
  3. 在.gitlab-ci.yml中配置SSH环境:
variables:
  GIT_SUBMODULE_STRATEGY: recursive

before_script:
  # 配置SSH目录和密钥权限
  - mkdir -p ~/.ssh
  - echo "${SSH_PRIVATE_KEY}" > ~/.ssh/id_rsa
  - chmod 600 ~/.ssh/id_rsa
  # 跳过GitLab实例的主机密钥验证(可信环境下可安全使用)
  - echo -e "Host gitlab.example.de\n\tStrictHostKeyChecking no\n" >> ~/.ssh/config
  # 同步并更新子模块
  - git submodule sync
  - git submodule update --init --recursive

方法3:修改.gitmodules固定带CI_JOB_TOKEN的地址

可以直接修改主仓库的.gitmodules文件,让CI自动用CI_JOB_TOKEN认证,本地单独配置开发用地址:

  1. 修改.gitmodules中的子模块URL:
[submodule "your-submodule"]
  path = path/to/your-submodule
  url = https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.example.de/user/example/example-group/project-development-setup.git
  1. 在.gitlab-ci.yml中启用子模块策略:
variables:
  GIT_SUBMODULE_STRATEGY: recursive
  1. 本地开发时,单独配置子模块的SSH地址避免报错:
git config submodule.your-submodule.url git@gitlab.example.de:user/example/example-group/project-development-setup.git

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 18:32:17