GitLab Runner改用SSH替代HTTP的配置问题排查
问题背景
自托管GitLab实例仅允许SSH访问仓库(已禁用HTTPS),将Proxmox上的Linux容器(系统版本:Linux runner 5.4.203-1-pve #1 SMP PVE 5.4.203-1 x86_64 x86_64 x86_64 GNU/Linux)作为GitLab Runner使用时,流水线执行失败。
首次报错信息
Fetching changes with git depth set to 20...
Reinitialized existing Git repository in /home/gitlab-runner/builds/gryU5_uD/0/path/to/repo/.git/
remote: HTTP Basic: Access denied. The provided password or token is incorrect or your account has 2FA enabled and you must use a personal access token instead of a password. See http://gitlab.company.cz/help/topics/git/troubleshooting_git#error-on-git-fetch-http-basic-access-denied
fatal: Authentication failed for 'http://gitlab.company.cz/path/to/repo.git/'
已尝试操作及二次报错
按GitLab官方手册添加Runner后,尝试了以下操作:
- 在
/etc/gitlab-runner/config.toml中配置clone_url = "ssh://git@gitlab.company.cz" - 将系统公钥添加为仓库部署密钥并授权
- 创建
~/.ssh/config并配置SSH连接参数
手动克隆仓库成功,但流水线仍失败;切换为gitlab-runner用户配置后,出现新报错:
Getting source from Git repository
00:00
Fetching changes with git depth set to 20...
Initialized empty Git repository in /home/gitlab-runner/builds/gryU5_uD/0/path/to/repo/.git/
Created fresh repository.
Host key verification failed.
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
最终解决步骤
核心问题是部署密钥未对gitlab-runner用户生效,需为该用户单独配置SSH环境:
切换到gitlab-runner用户
su - gitlab-runner # 若无法直接切换,使用:sudo -u gitlab-runner -i创建并配置
.ssh目录权限mkdir -p ~/.ssh chmod 700 ~/.ssh生成gitlab-runner专属SSH密钥
ssh-keygen -t rsa -b 4096 -C "gitlab-runner@your-runner-host"按提示回车,不要设置密钥密码(避免流水线需手动输入)。
添加公钥为GitLab仓库部署密钥
将生成的~/.ssh/id_rsa.pub内容复制,添加到GitLab仓库的部署密钥中,按需勾选"允许写入"(若流水线需要推送代码)。创建并配置
.ssh/config文件touch ~/.ssh/config chmod 600 ~/.ssh/config写入以下内容:
Host gitlab.company.cz Hostname gitlab.company.cz User git IdentityFile ~/.ssh/id_rsa StrictHostKeyChecking no(生产环境建议将
StrictHostKeyChecking改为accept-new,更安全)测试SSH连接
ssh git@gitlab.company.cz出现GitLab欢迎信息即表示连接成功。
重启GitLab Runner服务
sudo gitlab-runner restart
关键注意事项
- 禁止共用root用户的SSH密钥给gitlab-runner使用,权限隔离会导致认证失败
- 必须严格保证gitlab-runner用户的
.ssh目录权限为700,文件权限为600,否则SSH会拒绝加载密钥
内容的提问来源于stack exchange,提问作者kochy

