How to Use checkout scm in Jenkins Pipeline
Use
checkout scm inside a Jenkins Pipeline script to automatically clone the source code repository configured in the job. It simplifies fetching the code by using the job's SCM settings without extra configuration.Syntax
The checkout scm command is used inside a Jenkins Pipeline script to check out the source code from the repository configured in the Jenkins job's SCM settings.
It requires no parameters when you want to use the default SCM configured for the job.
checkout: Jenkins Pipeline step to fetch source code.scm: A built-in variable representing the SCM configuration of the current job.
groovy
checkout scm
Example
This example shows a simple Jenkins Pipeline script that uses checkout scm to clone the repository configured in the job. It then prints the current directory contents to confirm the checkout.
groovy
pipeline {
agent any
stages {
stage('Checkout') {
steps {
checkout scm
sh 'ls -la'
}
}
}
}Output
total 12
drwxrwxr-x 3 jenkins jenkins 4096 Apr 27 12:00 .
drwxrwxr-x 4 jenkins jenkins 4096 Apr 27 11:59 ..
-rw-r--r-- 1 jenkins jenkins 123 Apr 27 11:59 README.md
Common Pitfalls
Common mistakes when using checkout scm include:
- Using
checkout scmin a freestyle job without SCM configured, which causes errors. - Trying to pass parameters to
checkout scmwhen it expects no arguments. - Not configuring SCM in the Jenkins job, so
scmis undefined.
Always ensure your Jenkins job has SCM configured before using checkout scm.
groovy
pipeline {
agent any
stages {
stage('Checkout') {
steps {
// Wrong: passing parameters to checkout scm
// checkout scm(branch: 'main') // This will cause an error
// Right: just use checkout scm without parameters
checkout scm
}
}
}
}Quick Reference
| Command | Description |
|---|---|
| checkout scm | Checks out source code from the SCM configured in the Jenkins job |
| scm | Built-in variable representing the job's SCM configuration |
| checkout([$class: 'GitSCM', branches: [[name: 'main']]]) | Legacy way to specify Git checkout with parameters |
| sh 'ls -la' | Runs shell command to list files after checkout |
Key Takeaways
Use
checkout scm to clone the repository configured in your Jenkins job automatically.Do not pass parameters to
checkout scm; it uses the job's SCM settings by default.Ensure SCM is configured in the Jenkins job before using
checkout scm to avoid errors.Use
checkout scm inside a Pipeline script's steps block.For custom SCM checkout, use the
checkout step with explicit parameters instead.