Jenkins Pipeline as Code: Your First Jenkinsfile With Declarative Syntax, Stages, Steps and Post Actions

CI CD Pipelines with Jenkins 35 min min read Updated: Nov 17, 2026 Beginner
Jenkins Pipeline as Code: Your First Jenkinsfile With Declarative Syntax, Stages, Steps and Post Actions
Beginner Topic 1 of 5

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.

AdvantageWhy it matters
Versioned with the appThe pipeline that built version 1.4 is the one in the 1.4 commit
ReviewablePipeline changes go through pull requests
ReusableCopy, share, put the common parts in libraries
Survives server lossIf Jenkins dies, the definition is still in Git
Rich logicParallel work, conditions, retries, approvals

Two Syntaxes

DeclarativeScripted
Starts withpipeline { ... }node { ... }
StructureFixed, easy to read, validated before runningFree-form Groovy code
Best forAlmost everything. Start hereSpecial logic that declarative cannot express
Escape hatchscript { ... } block lets you use Groovy insideEverything 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

BlockMeaning
pipeline { }Required outer block for declarative syntax
agentWhere 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
Directivesenvironment, options, parameters, triggers, tools, when, input, parallel, matrix

Common Steps

StepExample
shsh 'mvn -B clean package' (Linux and Mac agents)
bat / powershellbat 'build.cmd' (Windows)
echoecho "Branch: ${env.BRANCH_NAME}"
checkout scmCheck out the repository the Jenkinsfile came from
gitgit url: 'https://...', branch: 'main'
archiveArtifactsarchiveArtifacts artifacts: 'target/*.jar'
junitjunit 'target/surefire-reports/*.xml'
stash / unstashMove files between stages or agents
dir('sub') { ... }Run steps in a sub-directory
sleep, retry, timeoutretry(3) { sh './flaky.sh' }
withCredentialsUse stored secrets safely
build job:Start another job
inputPause 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

  1. Commit the Jenkinsfile to your repository root
  2. Dashboard, New Item, name my-pipeline, choose Pipeline
  3. Under Pipeline, set *Definition* to Pipeline script from SCM, SCM Git, add the repository URL and credentials, branch */main, *Script Path* Jenkinsfile
  4. Save and Build Now
  5. 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

ErrorCauseFix
Expected a stepCode outside steps or a Groovy statement used directlyPut commands in steps; wrap Groovy in script { }
Missing required section agentNo agent definedAdd agent any (or none plus per-stage agents)
WorkflowScript: unexpected tokenMissing brace or quoteCheck matching { } and quotes; use the linter
No such DSL method 'xyz'Plugin for that step is not installedInstall the plugin or fix the name
script returned exit code 1A shell command failedRead the lines above it in the log
Scripts not permitted to use method ...Sandbox blocks the Groovy callUse a different step, or have an admin review in *Script Approval*
Single versus double quotes confusionGString expands ${} only in double quotesUse double quotes when you want Groovy variables, single quotes for shell variables

Practice Tasks

  1. Write a Jenkinsfile with three stages (Build, Test, Package) for any small project
  2. Add post blocks for always, success and failure and make one stage fail on purpose
  3. Create a Pipeline job from SCM and run it
  4. Use Pipeline Syntax to generate an archiveArtifacts step
  5. 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.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators