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

GitLab Runner推送代码到远程分支报Host key verification failed错误如何解决

问题原因及修复方案

你的报错Host key verification failed是SSH连接时无法验证远程主机身份导致的,核心问题出在配置逻辑错误:

  • 你错误地将SSH私钥$GIT_SSH_PRIV_KEY写入了~/.ssh/known_hosts文件,这个文件应该存储GitLab服务器的主机公钥,不是你的登录私钥,这是导致主机验证失败的直接原因。
  • SSH配置只写在了build-job的before_script里,执行推送操作的test-job2完全没有加载SSH配置,自然无法通过身份验证。
  • 你设置的远程推送地址git@gitlab/example_repo.git格式错误,缺少域名分隔的冒号,正确格式应为git@gitlab:example_repo.git,请替换为你实际的仓库SSH地址。

配置调整步骤

第一步:提前准备GitLab主机公钥

你可以在本地执行ssh-keyscan 你的GitLab域名(如果是公共GitLab就填gitlab.com)拿到公钥内容,存到项目的CI/CD变量中,变量名可以设为GITLAB_HOST_KEY。

第二步:调整.gitlab-ci.yml配置

你可以把SSH公共配置抽到全局before_script,或者直接放到执行推送的作业里,参考配置如下:

variables:
  GIT_STRATEGY: clone
# 全局before_script,所有作业都会执行
before_script:
  - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
  - eval $(ssh-agent -s)
  - echo "$GIT_SSH_PRIV_KEY" | tr -d '\r' | ssh-add -
  - mkdir -p ~/.ssh
  - chmod 700 ~/.ssh
  # 这里写入GitLab主机公钥,不要写入私钥
  - echo "$GITLAB_HOST_KEY" >> ~/.ssh/known_hosts
  - chmod 644 ~/.ssh/known_hosts
build-job:
  stage: build
  tags:
    - example_repo
  script:
    - echo "Hello!"
    - ls
    - python3 -V
    - pip3 list

test-job1:
  stage: test
  tags:
    - example_repo
  script:
    - python3 Experiments/ConfigAutomation.py

test-job2:
  stage: test
  tags:
    - example_repo
  script:
    - git config user.email "user@mymail.com"
    - git config user.name "username"
    - git checkout -b ci_processing
    - git show-ref
    - git remote -v
    # 修正远程地址格式,替换为你实际的仓库SSH地址
    - git remote set-url --push origin git@gitlab:example_repo.git
    - git add .
    - git commit --amend --reset-author --allow-empty -m "Files from runner to branch"
    - git push origin ci_processing:automation-test || true
    - echo "Pushed"

deploy-prod:
  stage: deploy
  tags:
    - example_repo
  script:
    - echo "This job deploys something."

close-conn:
  stage: .post
  tags:
    - example_repo
  script:
    - eval '/usr/bin/ssh-agent -k'

额外注意事项

  • 确保你使用的SSH私钥对应的账号对目标仓库有写入权限,优先使用项目部署密钥并授予写入权限。
  • 如果不需要跨作业复用其他内容,建议把test-job1和test-job2合并为同一个作业,避免生成的Excel文件在不同作业间丢失:GitLab CI默认每个作业都会重新克隆仓库,不同作业的工作空间是相互隔离的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 03:39:01