git fetch error in jenkins pipeline, use skipDefaultCheckout and dir directive for the fix

git fetch error in jenkins pipeline, use skipDefaultCheckout and dir directive for the fix
Photo by Roman Synkevych / Unsplash
Caused by: hudson.plugins.git.GitException: Command "git fetch --tags --progress git@github.com:xxx.git +refs/heads/*:refs/remotes/origin/*" returned status code 128:
stdout: 
stderr: ERROR: Repository not found.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Double confirm the repo url and credentials used for git command

you might see the above errors sometimes in your Jenkins pipeline. the error message might be right in case you do not put the right repository url or you don't have the right credential to access it.

Mixed .git under the same working repo

if you 100% sure, you have the right url and using the right credentials, but you still see such errors. Then check in another way. Make sure the working directory is empty before you checkout a new repo. In case there is already a .git folder before you checkout and the repo was for a different url, you might see the above error as well.

Jenkins pipeline skip default checkout and use dir change working directory

skipDefaultCheckout
Skip checking out code from source control by default in the agent directive. For example: options { skipDefaultCheckout() }

if the pipeline scripts is coming from a repo and the repo going to be in the pipelien is another one, you might encouter the above error as well. Since by default, the pipeline scripts repo will be checkout first. and then checkout the target repo to run build or run checkmarx scan if used as a webhook.

We can use the skipDefaultCheckout option to avoid these issue.

pipeline {
    agent { label "yourlabel" }
    options {
        skipDefaultCheckout(true)
    }
    stages {

And further more, we can leverage ```dir``` directive as well, to do the checkout in a separate working folder. so that even the target repo was checkout in the working space, it will won't affect the next job.

def workspaceDir = "${BUILD_ID}"
...
stage("SCM Checkout") {
            steps {
                dir(workspaceDir) {
                    git credentialsId: "your_credential", url: "${repository_ssh_url}", branch: "${branchName}"
                }
            }
        }

The ${BUILD_ID} is unique for the builds of the same jenkins job. so use it as workspace directory will make sure the code will be checkout in a sole folder even these builds running parallelly.

Subscribe to Post, Code and Quiet Time.

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe