I am trying to automate my deployment workflow and need to perform a Git checkout specifically using a Groovy script within a Jenkinsfile. I’ve tried using the generic 'git' step, but I need more control over the branch, credentials, and subdirectories. What is the proper syntax for the 'checkout' step in a scripted pipeline to ensure it handles private repositories and multiple branches correctly without failing the build?
3 answers
To perform a robust Git checkout in a Groovy script, you should use the checkout step instead of the simple git shorthand. The checkout step allows for a detailed scm map where you can specify the user remote configurations and branch details. For instance, you would use: checkout([$class: 'GitSCM', branches: [[name: '*/main']], userRemoteConfigs: [[url: 'https://github.com/user/repo.git', credentialsId: 'your-cred-id']]]). This approach is far more powerful because it supports behaviors like "Clean after checkout" or "Checking out to a sub-directory," which are essential for complex builds.
Using the Pipeline Syntax Snippet Generator in Jenkins is the best way to get the exact class names for your specific version of the Git plugin.
Does your Groovy script need to checkout multiple repositories into different folders within the same workspace, or are you just trying to switch branches on the primary project repository during the build process?
For a simple scripted pipeline, you can use git branch: 'development', credentialsId: 'my-creds', url: 'repo-url'. It’s much shorter than the full SCM class syntax if you don't need advanced extensions.
I agree with Kimberly for basic tasks, though as Cynthia pointed out, the full GitSCM class is the way to go if you are working in a professional Enterprise environment where you need to manage shallow clones or specific merge behaviors.
Jeffrey, that's a key question for workspace management. If Gregory needs to pull multiple repos, he must use the extensions parameter within the Groovy map to specify a RelativeTargetDirectory. Without this, each subsequent checkout will simply overwrite the previous one in the workspace root. It's a common mistake that leads to missing source files during the compilation phase of the pipeline.