Jenkins构建时报错 ERROR: Error fetching remote repo 'origin' hudson.plugins.git.GitException

Jenkins + GitLab持续集成时遇到如下错误:

ERROR: Error fetching remote repo 'origin'
hudson.plugins.git.GitException: Failed to fetch from ssh://[email protected]:2222/lucy/test.git
    at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:888)
    at hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:1155)
    at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1186)
    at org.jenkinsci.plugins.workflow.steps.scm.SCMStep.checkout(SCMStep.java:120)
    at org.jenkinsci.plugins.workflow.steps.scm.SCMStep$StepExecutionImpl.run(SCMStep.java:90)
    at org.jenkinsci.plugins.workflow.steps.scm.SCMStep$StepExecutionImpl.run(SCMStep.java:77)
    at org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution$1$1.call(SynchronousNonBlockingStepExecution.java:50)
    at hudson.security.ACL.impersonate(ACL.java:290)
    at org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution$1.run(SynchronousNonBlockingStepExecution.java:47)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: hudson.plugins.git.GitException: Command "git fetch --tags --progress ssh://[email protected]:2222/lucy/test.git +refs/heads/*:refs/remotes/origin/*" returned status code 128:
stdout: 
stderr: Permission denied (publickey).
fatal: Could not read from remote repository.
 
Please make sure you have the correct access rights
and the repository exists.
 
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:2016)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:1735)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.access$300(CliGitAPIImpl.java:72)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$1.execute(CliGitAPIImpl.java:420)
    at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:886)
    ... 13 more


解决方案:

添加Jenkins主机生成的公钥到GitLab:

Jenkins构建时报错 ERROR: Error fetching remote repo 'origin' hudson.plugins.git.GitException

在GitLab用户头像下拉框下点击Settings,之后在左侧边栏选择SSH Keys,输入复制的Key,点击Add Key:

Jenkins构建时报错 ERROR: Error fetching remote repo 'origin' hudson.plugins.git.GitException

 SSH Key添加成功:

Jenkins构建时报错 ERROR: Error fetching remote repo 'origin' hudson.plugins.git.GitException

 再次构建:

Jenkins构建时报错 ERROR: Error fetching remote repo 'origin' hudson.plugins.git.GitException