The declarative Jenkinsfile

Structure, options, and catching a broken file before it reaches a build.

Beginner12 min · lesson 4 of 15
Lesson files
The scripts, test data and local test servers this lesson uses, exactly as they ran on the lab machine (21 files, 7 KB): declarative.tar.gz. The lab VM shares no folders with your computer, so fetch them inside the VM: cd ~/lab && curl -fsSLO https://secopslog.com/lab-files/ci-jenkins/declarative.tar.gz && tar -xzf declarative.tar.gz, which creates ~/lab/declarative/. SHA-256: 538ac9f35c2653d587495bea6c4954fd07af79b087ec03076d709c5d4c3a1eb4

You push a Jenkinsfile change and wait for an agent, a checkout and ten minutes of tests, only to find a misplaced brace on the last stage. Now you fix it and wait again. Pipeline files are code, and like code they can be checked before they run. This lesson covers the shape of a declarative Jenkinsfile, the options worth setting on every pipeline, and how to catch a broken file in a second instead of ten minutes.

The shape of a pipeline

Jenkins has two pipeline syntaxes. Declarative, the pipeline { } form used here, has a fixed structure that Jenkins can validate. Scripted is free-form Groovy. Use declarative unless you have a specific reason not to, and drop into a script { } block for the rare step that needs real logic.

app/Jenkinsfile
pipeline {
agent none
options {
timeout(time: 10, unit: 'MINUTES')
disableConcurrentBuilds()
buildDiscarder(logRotator(numToKeepStr: '20'))
timestamps()
}
stages {
stage('Test') {
agent { label 'linux' }
steps {
sh 'echo testing on $NODE_NAME'
}
}
}
}
BlockWhat it does here
agent noneTakes no executor for the pipeline as a whole, so each stage picks its own
optionsSettings for the entire run
timeoutAborts a run that takes over 10 minutes, so a hang can't hold an executor forever
disableConcurrentBuildsStops two builds of this job overlapping
buildDiscarderKeeps the last 20 builds, so JENKINS_HOME doesn't grow without limit
timestampsPrefixes each console line with the time
stages / stageThe ordered phases shown in the UI
stepsThe actual work; sh runs a shell command

The agent none plus a per-stage agent pattern matters once you have approvals or long waits: a stage waiting for human input shouldn't occupy an executor. For a simple pipeline, agent { label 'linux' } at the top is fine, as you saw in earlier lessons.

Lint before you push

Jenkins exposes its validator over REST. Send it a file and it answers without running anything:

ubuntu@secopslog-cicd:~/lab/declarative · Jenkins 2.580.2
$ ./up.sh
agent lab-agent: online Jenkins 2.580.2 is up on http://127.0.0.1:8080
$ ./jk.sh /pipeline-model-converter/validate -X POST -F "jenkinsfile=<app/Jenkinsfile"
Jenkinsfile successfully validated.

Now a file someone wrote in a hurry, with sh directly inside the stage:

broken/Jenkinsfile
pipeline {
agent { label 'linux' }
stages {
stage('Test') {
sh 'echo no steps block around me'
}
}
}
ubuntu@secopslog-cicd:~/lab/declarative · Jenkins 2.580.2
$ ./jk.sh /pipeline-model-converter/validate -X POST -F "jenkinsfile=<broken/Jenkinsfile"
Errors encountered validating Jenkinsfile: WorkflowScript: 4: Unknown stage section "sh". Starting with version 0.5, steps in a stage must be in a ‘steps’ block. @ line 4, column 5. stage('Test') { ^ WorkflowScript: 4: Expected one of "steps", "stages", or "parallel" for stage "Test" @ line 4, column 5. stage('Test') { ^

Both errors name the fix: steps belong in a steps block. Look at the exit status, though: the validator exits 0 even for an invalid file, because the HTTP request itself succeeded. To use this in a pre-commit hook or CI check, test the text for successfully validated and not the exit code. The linter needs a running Jenkins with your plugins, since available steps depend on them.

One more structural rule the linter enforces: a stage does its work in exactly one form. It holds steps, nested stages, parallel branches or a matrix, never two of them. This file puts steps and parallel in the same stage:

twoforms/Jenkinsfile
pipeline {
agent { label 'linux' }
stages {
stage('Test') {
steps {
sh 'echo unit'
}
parallel {
stage('Lint') { steps { sh 'echo lint' } }
}
}
}
}
ubuntu@secopslog-cicd:~/lab/declarative · Jenkins 2.580.2
$ ./jk.sh /pipeline-model-converter/validate -X POST -F "jenkinsfile=<twoforms/Jenkinsfile"
Errors encountered validating Jenkinsfile: WorkflowScript: 4: Only one of "matrix", "parallel", "stages", or "steps" allowed for stage "Test" @ line 4, column 5. stage('Test') { ^

To run a step before parallel branches, give it its own stage first.

A good run, then the same mistake without the linter

ubuntu@secopslog-cicd:~/lab/declarative · Jenkins 2.580.2
$ ./seed.sh app app/ && ./newjob.sh app app && ./run-job.sh app
pushed app: 18f3bf8 first commit job app reads Jenkinsfile from git://git/app.git Started by user admin [Pipeline] timeout Timeout set to expire in 10 min [Pipeline] timestamps [2026-11-08T02:49:52.008Z] Running on lab-agent in /home/jenkins/agent/workspace/app [2026-11-08T02:49:57.369Z] + echo testing on lab-agent [2026-11-08T02:49:57.369Z] testing on lab-agent Finished: SUCCESS build #1 result: SUCCESS

Timeout set to expire in 10 min is the timeout option taking effect, and each line now has a timestamp from timestamps(). Now push the broken file and skip the lint step:

ubuntu@secopslog-cicd:~/lab/declarative · Jenkins 2.580.2
$ cp broken/Jenkinsfile app/Jenkinsfile && ./commit.sh app/ "lose the steps block"
pushed: 8c8f3d8 lose the steps block
$ ./run-job.sh app
Started by user admin org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: WorkflowScript: 4: Unknown stage section "sh". Starting with version 0.5, steps in a stage must be in a ‘steps’ block. @ line 4, column 5. stage('Test') { ^ WorkflowScript: 4: Expected one of "steps", "stages", or "parallel" for stage "Test" @ line 4, column 5. stage('Test') { ^ 2 errors ... Finished: FAILURE build #2 result: FAILURE

It fails with the same messages, just wrapped in a stack trace, and before any stage starts: no agent was used and no step ran. A declarative file is compiled as a whole first, which is why a mistake in the last stage still fails at the start of the build. Read the first WorkflowScript: line and ignore the Java frames below it.

Validity isn't correctness, though. The linter checks structure and doesn't run anything, so it can't tell you that a shell command is wrong or a credential ID is misspelled. Those still appear only when the step runs.

A post block with no node

agent none has a consequence for pipeline-level post blocks: they run outside every stage, so no agent is allocated for them. A step that needs a workspace, such as sh, has nowhere to run. This file is valid and its stage passes:

nonode/Jenkinsfile
pipeline {
agent none
stages {
stage('Test') {
agent { label 'linux' }
steps {
sh 'echo testing on $NODE_NAME'
}
}
}
post {
always {
sh 'rm -rf build'
}
}
}
ubuntu@secopslog-cicd:~/lab/declarative · Jenkins 2.580.2
$ cp nonode/Jenkinsfile app/Jenkinsfile && ./commit.sh app/ "clean up in post" && ./run-job.sh app
pushed: 04a5520 clean up in post Started by user admin Running on lab-agent in /home/jenkins/agent/workspace/app + echo testing on lab-agent testing on lab-agent [Pipeline] error Error when executing always post condition: ... hudson.AbortException: Attempted to execute a step that requires a node context while ‘agent none’ was specified. Be sure to specify your own ‘node { ... }’ blocks when using ‘agent none’. ... ERROR: Attempted to execute a step that requires a node context while ‘agent none’ was specified. Be sure to specify your own ‘node { ... }’ blocks when using ‘agent none’. Finished: FAILURE build #3 result: FAILURE

The Test stage ran on lab-agent and passed. Then the always block failed with Attempted to execute a step that requires a node context while ‘agent none’ was specified, and the whole build is FAILURE. With agent none, put cleanup in the stage's own post block, which runs on that stage's agent, or use cleanWs() there.

Hands-on

Start a fresh lab with the original app/Jenkinsfile (git -C app checkout HEAD~2 -- Jenkinsfile brings it back). Delete the closing brace of the options block in app/Jenkinsfile and run the linter, then restore it. Then add a stage named Lint with a misspelled step, shh 'true'. Does the linter catch it? Run the build and find out at which point the misspelled step fails. Finish with ./down.sh.

What you should see: without the brace, the linter reports expecting '}', found '' at line 17, the end of the file, not at line 8 where the brace is missing, so look above the line it names. The misspelled step passes the linter with Jenkinsfile successfully validated. The build fails only when it reaches the step, after an agent was allocated, with No such DSL method 'shh' found among steps, and the Test stage is skipped. The linter checks structure, not step names.

Remember

Put timeout and buildDiscarder in every pipeline, because the default for both is forever. Lint before pushing and check the response text, not the exit code. Only a run proves the commands work.

Quick check
01A pre-commit hook runs the validator with curl -f and blocks the commit on a non-zero exit. Developers report that invalid Jenkinsfiles get through. Why?
Incorrect — -f works with POST. The request is sent and answered.
Incorrect — It read the file correctly in the lab and reported the exact errors.
Correct — The verdict is in the response body, so the hook must check for successfully validated.
Incorrect — There is no such cache. The lab validated a good file, then a bad one, with the correct answers.
02A pipeline waits for a manual approval that can take a day. Why choose agent none with an agent on each working stage?
Correct — With per-stage agents, the approval stage holds nothing while people decide.
Incorrect — They can run under one. The objection is the wasted executor, not an error.
Incorrect — A fresh node allocation can make a stage slower, and speed is not the reason here.
Incorrect — The input step needs no node and no secrets. Nothing is gained on that side.
03A Jenkinsfile has a structural mistake in its final stage. When does the build fail?
Incorrect — That is how a bad shell command behaves. Structure is checked before anything runs.
Incorrect — They do not skip. The lab build ended in FAILURE.
Incorrect — Nothing validates at push time unless you add a hook yourself.
Correct — No agent is taken and no stage runs, and the first WorkflowScript: line has the reason.

Related