Pipeline as code means the build definition is versioned, reviewed and branched with the application.
Pasting scripts into the job configuration doesn't scale. Instead commit a file named Jenkinsfile at the repository root and configure the job's definition as Pipeline script from SCM: repository URL, credentials, branch and script path.
At build time Jenkins fetches the Jenkinsfile from that branch, and declarative pipelines automatically check out the same commit into the workspace (the implicit Declarative: Checkout SCM stage), so sh 'make' sees your code. In scripted code or custom stages, checkout scm does the same explicitly.
How builds start:
- Webhooks: GitHub, GitLab or Bitbucket send an HTTP request to Jenkins on every push (with the corresponding plugin, for example
https://jenkins.example.com/github-webhook/). Instant and cheap. - Polling:
pollSCM('H/5 * * * *')asks the repository for changes every few minutes. Use only when the Git server can't reach Jenkins.
Environment variables describe the build: BUILD_NUMBER, BUILD_URL, WORKSPACE, JOB_NAME, and with Git GIT_COMMIT and GIT_BRANCH. Access them as env.NAME in Groovy or $NAME in sh.
Changing the build now means a commit: reviewed in a pull request, tested on a branch and revertable like any code.
Example
// Jenkinsfile at the repository root
pipeline {
agent any
triggers {
pollSCM('H/5 * * * *') // only if webhooks are impossible
}
stages {
stage('Info') {
steps {
sh 'echo "commit $GIT_COMMIT on $GIT_BRANCH"'
// commit 1a2b3c4d... on origin/main
sh 'ls' // the repository is already checked out
}
}
stage('Build') {
steps { sh 'make build' }
}
}
}Remember
- Commit a Jenkinsfile and use Pipeline script from SCM
- Declarative pipelines check out the same commit automatically
- Prefer webhooks to polling
Watch out for
- Polling every minute across hundreds of jobs, overloading both Jenkins and the Git server.