Pipeline as Code
Treat your pipeline like application code: version it, review it, and keep it in the repository.
Pipeline as code is the philosophy that your CI/CD process should be defined in files, stored in version control, and treated with the same care as application code.
Principles
- Keep the Jenkinsfile in the repo — never configure real pipelines only through the UI.
- Review changes — pipeline changes go through pull requests like any code.
- Small, readable stages — favor clarity over cleverness.
- Fail fast — put quick checks (lint, unit tests) early so problems surface sooner.
- Keep it DRY — extract repeated logic into shared libraries.
Benefits
Every pipeline change is tracked, reviewable, and reversible. New team members can read the Jenkinsfile to understand exactly how the project is built and deployed.
Example
# Good structure for pipeline-as-code:
#
# my-app/
# |-- Jenkinsfile <-- version controlled
# |-- scripts/
# | |-- build.sh <-- logic kept out of the Jenkinsfile
# | +-- deploy.sh
# +-- src/
#
# The Jenkinsfile orchestrates; scripts do the heavy lifting.When to use it
- A team code-reviews all Jenkinsfile changes in pull requests so no CI/CD change bypasses the approval process.
- A developer rolls back a broken pipeline by reverting the Jenkinsfile commit, the same way they revert application code.
- An engineer diffs two Jenkinsfile versions in Git to understand exactly what changed between a passing and a failing build.
More examples
Jenkinsfile committed at root
Confirms the Jenkinsfile is version-controlled and validates its syntax before committing.
# Verify Jenkinsfile is tracked by Git
git ls-files Jenkinsfile
# Output: Jenkinsfile
# Validate syntax before pushing
curl -X POST \
http://localhost:8080/pipeline-model-converter/validate \
--user admin:$TOKEN -F "jenkinsfile=<Jenkinsfile"Pipeline job pointing to SCM
Configures a pipeline job via Job DSL to read its definition from the Jenkinsfile in the Git repository.
// Job DSL: configure a Pipeline job to read Jenkinsfile from SCM
pipelineJob('myapp-pipeline') {
definition {
cpsScm {
scm {
git {
remote { url('https://github.com/org/myapp.git') }
branch('main')
}
}
scriptPath('Jenkinsfile')
}
}
}Branch-specific pipeline logic
Uses a when condition in the Jenkinsfile itself to enforce that deployments only happen from the main branch.
pipeline {
agent any
stages {
stage('Build') { steps { sh 'mvn package' } }
stage('Deploy') {
when { branch 'main' }
steps { sh './deploy-prod.sh' }
}
}
}
Discussion