Jenkins Pipeline as Code: Your First Jenkinsfile With Declarative Syntax, Stages, Steps and Post Actions
What Is a Jenkinsfile?
A Jenkinsfile is a text file in the root of your repository that describes your whole CI/CD process as code. Jenkins reads it, runs it and shows the stages. Because it lives in Git you get history, code review, branches and rollback for your pipeline, just like for your application.
| Advantage | Why it matters |
| Versioned with the app | The pipeline that built version 1.4 is the one in the 1.4 commit |
| Reviewable | Pipeline changes go through pull requests |
| Reusable | Copy, share, put the common parts in libraries |
| Survives server loss | If Jenkins dies, the definition is still in Git |
| Rich logic | Parallel work, conditions, retries, approvals |
Two Syntaxes
| Declarative | Scripted |
| Starts with | pipeline { ... } | node { ... } |
| Structure | Fixed, easy to read, validated before running | Free-form Groovy code |
| Best for | Almost everything. Start here | Special logic that declarative cannot express |
| Escape hatch | script { ... } block lets you use Groovy inside | Everything is Groovy |
Your First Jenkinsfile
groovy
pipeline {
agent any
stages {
stage('Checkout') {
steps {
checkout scm
sh 'ls -la'
}
}
stage('Build') {
steps {
echo 'Building...'
sh 'make build'
}
}
stage('Test') {
steps {
sh 'make test'
}
}
stage('Package') {
steps {
sh 'tar czf app.tgz build/'
archiveArtifacts artifacts: 'app.tgz', fingerprint: true
}
}
}
post {
always { echo 'Pipeline finished' }
success { echo 'All good' }
failure { echo 'Something failed' }
}
}
The Building Blocks
| Block | Meaning |
pipeline { } | Required outer block for declarative syntax |
agent | Where the pipeline (or a stage) runs: any, none, { label 'linux' }, { docker { image '...' } } |
stages { } | Contains one or more stage |
stage('Name') { } | A named phase. Each stage appears as a column in the Stage View |
steps { } | The actual commands inside a stage |
post { } | Actions after the stage or pipeline: always, success, failure, unstable, changed, fixed, regression, aborted, cleanup |
| Directives | environment, options, parameters, triggers, tools, when, input, parallel, matrix |
Common Steps
| Step | Example |
sh | sh 'mvn -B clean package' (Linux and Mac agents) |
bat / powershell | bat 'build.cmd' (Windows) |
echo | echo "Branch: ${env.BRANCH_NAME}" |
checkout scm | Check out the repository the Jenkinsfile came from |
git | git url: 'https://...', branch: 'main' |
archiveArtifacts | archiveArtifacts artifacts: 'target/*.jar' |
junit | junit 'target/surefire-reports/*.xml' |
stash / unstash | Move files between stages or agents |
dir('sub') { ... } | Run steps in a sub-directory |
sleep, retry, timeout | retry(3) { sh './flaky.sh' } |
withCredentials | Use stored secrets safely |
build job: | Start another job |
input | Pause and ask a person to approve |
The post Section in Detail
groovy
post {
always {
junit allowEmptyResults: true, testResults: '**/target/surefire-reports/*.xml'
cleanWs()
}
success { slackSend color: 'good', message: "OK ${env.JOB_NAME} #${env.BUILD_NUMBER}" }
failure { mail to: 'team@example.com', subject: "FAILED ${env.JOB_NAME}", body: "${env.BUILD_URL}" }
unstable { echo 'Tests failed but the build ran' }
fixed { echo 'Back to green after a failure' }
regression{ echo 'Was green, now not' }
}
always runs whatever happens, so put test report collection and cleanup there
post order: always, changed, fixed, regression, aborted, failure, success, unstable, unsuccessful, then cleanup last
cleanup runs after all other post conditions, even if they fail
Create a Pipeline Job
- Commit the
Jenkinsfile to your repository root
- Dashboard, New Item, name
my-pipeline, choose Pipeline
- Under Pipeline, set *Definition* to Pipeline script from SCM, SCM Git, add the repository URL and credentials, branch
*/main, *Script Path* Jenkinsfile
- Save and Build Now
- Open the build: the Stage View shows each stage's time and result. Click a stage to see its logs; Pipeline Overview or Blue Ocean style views show a graph
Quick experiments: For learning you can choose *Pipeline script* and paste the code into the job. Switch to *from SCM* as soon as the pipeline is real.
Pipeline Syntax Helper
Every job has a Pipeline Syntax link (also at JENKINS_URL/pipeline-syntax). Choose a step, fill the form and it generates the exact code for you, including all options of plugins. There is also a Declarative Directive Generator and a global variable reference. Use these instead of guessing.
Validate Before You Commit
bash
# Lint a Jenkinsfile on the server (needs an API token)
curl -s -X POST -u alice:TOKEN -F "jenkinsfile=<Jenkinsfile" https://jenkins.example.com/pipeline-model-converter/validate
# Or use the Jenkins CLI
java -jar jenkins-cli.jar -s https://jenkins.example.com/ -auth alice:TOKEN declarative-linter < Jenkinsfile
Typical Errors and Fixes
| Error | Cause | Fix |
Expected a step | Code outside steps or a Groovy statement used directly | Put commands in steps; wrap Groovy in script { } |
Missing required section agent | No agent defined | Add agent any (or none plus per-stage agents) |
WorkflowScript: unexpected token | Missing brace or quote | Check matching { } and quotes; use the linter |
No such DSL method 'xyz' | Plugin for that step is not installed | Install the plugin or fix the name |
script returned exit code 1 | A shell command failed | Read the lines above it in the log |
Scripts not permitted to use method ... | Sandbox blocks the Groovy call | Use a different step, or have an admin review in *Script Approval* |
| Single versus double quotes confusion | GString expands ${} only in double quotes | Use double quotes when you want Groovy variables, single quotes for shell variables |
Practice Tasks
- Write a Jenkinsfile with three stages (Build, Test, Package) for any small project
- Add
post blocks for always, success and failure and make one stage fail on purpose
- Create a Pipeline job from SCM and run it
- Use Pipeline Syntax to generate an
archiveArtifacts step
- Lint your file with the declarative linter
Conclusion
A Jenkinsfile defines your CI/CD process as code in Git. Declarative syntax uses pipeline, agent, stages, stage, steps and post, and is validated before it runs. Use the Pipeline Syntax generator, collect test reports in post always, and learn the common error messages.
Quick Summary: Jenkinsfile in Git; declarative vs scripted; blocks; common steps; post conditions; pipeline from SCM; syntax generator; linter; errors.