How to checkout the latest gerrit patchset

Here is my pipeline and error log:

Pipeline script

Pipeline scirpt
pipeline {
    agent any
    stages {
        stage('Checkout Gerrit Latest PatchSet') {
            steps {
                echo "Gerrit: ${GERRIT_HOST}:${GERRIT_PORT}"
                echo "Project: ${GERRIT_PROJECT}\nBranch: ${GERRIT_BRANCH}\nRefSpec: ${GERRIT_REFSPEC}"
                checkout([
                    $class: 'GitSCM',
                    branches: [[name: "${GERRIT_BRANCH}"]],
                    doGenerateSubmoduleConfigurations: false,
                    extensions: [[$class: 'CleanBeforeCheckout']],
                    submoduleCfg: [],
                    userRemoteConfigs: [[
                        credentialsId: 'jenkins-rsa',
                        refspec: "${GERRIT_REFSPEC}",
                        url: 'ssh://jenkins@${GERRIT_HOST}:${GERRIT_PORT}/${GERRIT_PROJECT}'
                    ]]
                ])
            }
        }
        stage('SonarQube Analysis') {
            when {
                expression { return fileExists('sonar-project.properties') }
            }
            steps {
                script {
                    def scannerHome = tool 'SonarScanner';
                    withSonarQubeEnv() {
                       sh "${scannerHome}/bin/sonar-scanner"
                    }
                }
            }
        }
    }
}

error log

Jenkins Job error log

Started by user Administrator Replayed #121 [Pipeline] Start of Pipeline [Pipeline] node Running on Jenkins in /var/jenkins_home/workspace/Sonar Scan [Pipeline] { [Pipeline] stage [Pipeline] { (Checkout Gerrit Latest PatchSet) [Pipeline] echo Gerrit: gerrit.m.local:29418 [Pipeline] echo Project: sdk Branch: master RefSpec: refs/changes/82/182/2 [Pipeline] checkout > git rev-parse --resolve-git-dir /var/jenkins_home/workspace/Sonar Scan/.git # timeout=10 Fetching changes from the remote Git repository > git config remote.origin.url ssh:///jenkins@gerrit.m.local:29418/sdk # timeout=10 Cleaning workspace > git rev-parse --verify HEAD # timeout=10 Resetting working tree > git reset --hard # timeout=10 > git clean -fdx # timeout=10 Fetching upstream changes from ssh:///jenkins@gerrit.m.local:29418/sdk > git --version # timeout=10 > git --version # ‘git version 2.30.2’ > git fetch --tags --force --progress – ssh:///jenkins@gerrit.m.local:29418/sdk refs/changes/82/182/2 # timeout=10 ERROR: Error fetching remote repo ‘origin’ hudson.plugins.git.GitException: Failed to fetch from ssh:///jenkins@gerrit.m.local:29418/sdk at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:1003) at hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:1245) at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1309) at org.jenkinsci.plugins.workflow.steps.scm.SCMStep.checkout(SCMStep.java:129) at org.jenkinsci.plugins.workflow.steps.scm.SCMStep$StepExecutionImpl.run(SCMStep.java:97) at org.jenkinsci.plugins.workflow.steps.scm.SCMStep$StepExecutionImpl.run(SCMStep.java:84) at org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution.lambda$start$0(SynchronousNonBlockingStepExecution.java:47) at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:829) Caused by: hudson.plugins.git.GitException: Command “git fetch --tags --force --progress – ssh:///jenkins@gerrit.m.local:29418/sdk refs/changes/82/182/2” returned status code 128: stdout: stderr: ssh: Could not resolve hostname : Name or service not known 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:2732) at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:2109) at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$1.execute(CliGitAPIImpl.java:623) at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:1001) … 11 more [Pipeline] } [Pipeline] // stage [Pipeline] stage [Pipeline] { (SonarQube Analysis) Stage “SonarQube Analysis” skipped due to earlier failure(s) [Pipeline] } [Pipeline] // stage [Pipeline] } [Pipeline] // node [Pipeline] End of Pipeline ERROR: Error fetching remote repo ‘origin’ Finished: FAILURE

BTW,

  1. Login docker container, run ssh command is okay.
root@d7fcc9e730e7:/# ssh -i /var/jenkins_home/.ssh/id_rsa -p 29418 jenkins@gerrit.m.local

  ****    Welcome to Gerrit Code Review    ****

  Hi jenkins, you have successfully connected over SSH.

  Unfortunately, interactive shells are disabled.
  To clone a hosted Git repository, use:

  git clone ssh://jenkins@gerrit.m.local:29418/REPOSITORY_NAME.git

Connection to gerrit.m.local closed.
  1. checkout scm in Jenkinsfile is okay
  2. ssh:///jenkins@gerrit.m.local:29418, there are three forward slashes, I don’t know if this will have side effects

I thought ssh was default, so you just do git clone jenkins@gerrit.host?

Not work. If removed ssh://

url: 'jenkins@${GERRIT_HOST}:${GERRIT_PORT}/${GERRIT_PROJECT}'

The SSH clone seems to have a problem somewhere, but I haven’t found a solution yet.
Using anonymous http, it works fine.
Here is my solution:

pipeline {
    agent any
    stages {
        stage('Clean Workspace') {
            steps {
                deleteDir()
            }
        }
        stage('Checkout Gerrit Latest PatchSet') {
            steps {
                echo "Gerrit: ${GERRIT_HOST}:${GERRIT_PORT}"
                echo "Project: ${GERRIT_PROJECT}\nBranch: ${GERRIT_BRANCH}\nRefSpec: ${GERRIT_REFSPEC}"
                checkout([
                    $class: 'GitSCM',
                    branches: [[name: "${GERRIT_BRANCH}"]],
                    doGenerateSubmoduleConfigurations: false,
                    extensions: [[$class: 'CleanBeforeCheckout']],
                    submoduleCfg: [],
                    userRemoteConfigs: [[
                        refspec: "${GERRIT_REFSPEC}",
                        url: 'http://${GERRIT_HOST}/${GERRIT_PROJECT}'
                    ]]
                ])
            }
        }
        stage('SonarQube Analysis') {
            when {
                expression { return fileExists('sonar-project.properties') }
            }
            steps {
                script {
                    def scannerHome = tool 'SonarScanner';
                    withSonarQubeEnv() {
                       sh "${scannerHome}/bin/sonar-scanner"
                    }
                }
            }
        }
    }
}

after checkout, add this

                // add this 
                script {
                    if (env.GERRIT_CHANGE_NUMBER && env.GERRIT_PATCHSET_NUMBER) {
                        def changeBranch = "change-${GERRIT_CHANGE_NUMBER}-${GERRIT_PATCHSET_NUMBER}"
                        sh "git fetch http://${GERRIT_HOST}/${GERRIT_PROJECT} ${GERRIT_REFSPEC}"
                        sh "git checkout -b ${changeBranch} FETCH_HEAD"
                    }
                }

If Jenkinsfile, try this:

        stage('Checkout') {
            steps {
                checkout scm
                script {
                    if (env.GERRIT_CHANGE_NUMBER && env.GERRIT_PATCHSET_NUMBER) {
                        def changeBranch = "change-${GERRIT_CHANGE_NUMBER}-${GERRIT_PATCHSET_NUMBER}"
                        sh "git fetch http://${GERRIT_HOST}/${GERRIT_PROJECT} ${GERRIT_REFSPEC}"
                        sh "git checkout -b ${changeBranch} FETCH_HEAD"
                    }
                }
                sh 'git submodule update --init'
            }
        }

Or this:

pipeline {
    agent any
    stages {
        stage('Checkout PatchSet') {
            steps {
                checkout scmGit(
                    branches: [[name: 'FETCH_HEAD']],
                    extensions: [],
                    userRemoteConfigs: [[
                        refspec: '${GERRIT_REFSPEC}',
                        url: 'https://${GERRIT_HOST}/${GERRIT_PROJECT}'
                    ]]
                )
            }
        }
    }
}