So far, the orders-api Jenkinsfile uses only four words of declarative syntax: pipeline, agent, stages/stage and steps. With them you have built a build, test and package process, but the orders-api-build Freestyle job still has things the pipeline lacks: parameters, a nightly build, polling, a timeout, timestamps and a retention policy, all configured in forms. In this lesson you will go through the complete anatomy of a declarative pipeline: its sections (the blocks that hold the structure and the steps) and its directives (the blocks that configure how it behaves). You will learn where each one can go and in what order, and with that knowledge you will migrate everything the Freestyle job had in the interface into the Jenkinsfile, so that the job configuration is, at last, versioned alongside the code.
Anatomy of a Declarative Pipeline
This skeleton shows all the pieces you will see in this lesson, in the conventional order. It is not a Jenkinsfile to run, but a map:
pipeline { // Root section (required)
agent any // Section: where it runs (required)
environment { ... } // Directive: environment variables
options { ... } // Directive: job and build options
parameters { ... } // Directive: build parameters
triggers { ... } // Directive: automatic triggers
tools { ... } // Directive: tools installed by Jenkins
stages { // Section: list of stages (required)
stage('Name') { // A stage
agent { ... } // Optional section: the stage's own agent
environment { ... } // Optional directive
tools { ... } // Optional directive
input { ... } // Optional directive: ask for confirmation
options { ... } // Optional directive: stage options
when { ... } // Optional directive: condition
steps { ... } // Section: the steps (required in a normal stage)
post { ... } // Optional section: actions when the stage ends
}
}
post { ... } // Section: actions when the build ends
}The same structure as a tree:
flowchart TB
P["pipeline"] --> A["agent"]
P --> D["directives: environment, options,<br/>parameters, triggers, tools"]
P --> S["stages"]
P --> PO["post"]
S --> ST["stage('...')"]
ST --> SA["agent (optional)"]
ST --> SD["directives: environment, tools,<br/>input, options, when"]
ST --> SS["steps"]
ST --> SP["post (optional)"]
SS --> PA["steps: sh, echo, archiveArtifacts, script..."]
The difference between the two kinds of block:
- Sections: hold the structure of the process and the steps (
agent,stages,steps,post). - Directives: configure behavior, but do not contain steps (
environment,options,parameters,triggers,tools,input,when).
Sections: pipeline, agent, stages, stage, steps and post
| Section | What it contains | Required? | Where it goes |
|---|---|---|---|
pipeline |
The whole definition | Yes | Root of the Jenkinsfile |
agent |
Where it runs | Yes at pipeline level; optional in stage |
pipeline and stage |
stages |
One or more stage blocks |
Yes | pipeline (and inside a stage, for nested stages) |
stage |
A named stage | At least one | Inside stages |
steps |
The stage's steps | Yes in a normal stage | Inside stage |
post |
Actions depending on the result | No | pipeline and stage |
You already know all of them except post, which goes at the end of the pipeline or of a stage and defines actions that run when it finishes, depending on the result (always, on failure, on recovery...). It is important enough to take up a good part of the next lesson, Flow Control: when, post and Error Handling.
The agent Section in Detail
agent specifies which node the pipeline or a stage runs on. The most common forms:
| Form | Meaning | When to use it |
|---|---|---|
agent any |
Any node with a free executor | Simple installations; what orders-api uses today |
agent none |
No global agent; each stage must declare its own | When stages need different nodes, or to avoid holding an executor while waiting |
agent { label 'linux' } |
A node with the linux label |
The usual choice in production |
agent { docker { ... } } |
A Docker container | Jenkins with Docker |
agent { kubernetes { ... } } |
A Kubernetes pod | Jenkins and Kubernetes |
Labels: Not Yet
At TecnoShop we are sticking with agent any, which today means "the built-in node". The recommended form is agent { label 'linux' }, but there is no node with that label yet: if you used it now, the build would sit in the queue indefinitely with the message There are no nodes with the label 'linux'. You will create the linux-agent-01 agent with the linux label in Managing Jenkins Nodes and Agents, and from then on the examples will use that form. Remember the warning from module 1: running builds on the controller is not recommended in production.
Stage-Level Agent
With agent none at the root, each stage chooses its own agent:
pipeline {
agent none
stages {
stage('Build') {
agent any
steps {
sh './mvnw -B clean compile'
}
}
stage('Report') {
agent any
steps {
echo 'This stage could run on a different node'
}
}
}
}agent none: the pipeline does not hold any executor globally.agent anyin eachstage: each stage requests its own executor, and each one performs its own implicit checkout.- Important consequence: two stages may end up on different nodes (and workspaces), so the files one generates are not available in the other. To pass files between stages there is
stash/unstash, which you will see in Pipeline Stages and Steps in Depth.
For orders-api, with all stages on the same node and sharing target/, agent any at pipeline level is the right choice.
The environment Directive (the Basics)
environment defines environment variables available to the steps:
pipeline {
agent any
environment {
APP_NAME = 'orders-api'
}
stages {
stage('Info') {
steps {
sh 'echo "Application: $APP_NAME"'
echo "Application: ${env.APP_NAME}"
}
}
}
}- Each
NAME = 'value'line creates an environment variable. - Inside
sh, bash sees it as$APP_NAME; in Groovy it is read withenv.APP_NAME. - It can go at
pipelinelevel (visible in every stage) or atstagelevel (only in that stage).
We do not need it in orders-api for now. Predefined and computed environment variables, their scope and their use with credentials are covered in Using Environment Variables and Credentials and Secrets Management.
The options Directive
options configures the behavior of the job and the build. Many options are equivalent to checkboxes in a Freestyle job's configuration.
| Option | What it does | Freestyle equivalent |
|---|---|---|
timestamps() |
Adds the time to every console line (Timestamper plugin) | Add timestamps to the Console Output |
timeout(time: 20, unit: 'MINUTES') |
Aborts the build if it exceeds that time | Terminate a build if it's stuck |
buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5')) |
Retention policy: keeps 30 builds, and only 5 with artifacts | Discard old builds |
disableConcurrentBuilds() |
Prevents two simultaneous builds of the job; the new one waits in the queue | Default Freestyle behavior |
skipDefaultCheckout() |
Disables the implicit Declarative: Checkout SCM checkout |
— |
retry(3) |
If the build fails, repeats it in full, up to 3 attempts in total | — |
quietPeriod(30) |
Waits 30 seconds in the queue before starting | Quiet period |
Details worth knowing:
timeoutacceptsSECONDS,MINUTESandHOURSas units, among others. When it runs out, the build ends as ABORTED (gray), not FAILURE.- In
logRotator, the values are written as strings ('30', not30). BesidesnumToKeepStrandartifactNumToKeepStr, there aredaysToKeepStrandartifactDaysToKeepStr. disableConcurrentBuilds()acceptsabortPrevious: truein current versions: instead of waiting, the new build aborts the one in progress. Useful for branches with many pushes in a row; fororders-apiwe prefer to wait.retryrepeats the entire build, even if the failure is a broken test. Use it with great caution; it is usually better to retry only the problematic step with theretrystep (03-05).- There are other options you will see later:
skipStagesAfterUnstable()(03-05),preserveStashes()(04-01),parallelsAlwaysFailFast()(04-02) andcheckoutToSubdirectory('dir').
Stage-Level options
Some options can also go inside a stage and affect only that stage: timeout, retry, timestamps and skipDefaultCheckout. This is very useful for putting bounds on a specific stage:
- If the tests hang (for example, waiting for a connection that never comes), they are aborted after 10 minutes, without waiting for the global 20-minute limit.
Job management options, such as buildDiscarder or disableConcurrentBuilds, can only go at pipeline level.
The parameters Directive
parameters declares the build parameters, just like This project is parameterized in the Freestyle job from 02-03.
parameters {
booleanParam(name: 'RUN_TESTS', defaultValue: true,
description: 'Uncheck only to quickly verify that the code compiles. Never for a build that is going to be deployed.')
choice(name: 'ENVIRONMENT', choices: ['dev', 'staging', 'production'],
description: 'Target environment. Informational only for now.')
}booleanParam(...): a checkbox.defaultValue: trueleaves it checked by default.choice(...): a closed list.choicesis a Groovy list ([...]), and the first value (dev) is the default. The rule from 02-03 still applies: the first one should be the least dangerous.- To split a long line, just continue on the next line after a comma; Groovy understands that the call continues.
Other available types: string(name: ..., defaultValue: ..., description: ...), text(...) (multi-line) and password(...) (with the same warning as in the Freestyle job: it is not a secure mechanism for secrets).
Using Parameters: params
Values are read with the global variable params:
There is an important difference from the Freestyle job. There, in bash, the Boolean Parameter arrived as the string true or false. In params, by contrast, params.RUN_TESTS is a real Groovy boolean that you can use directly in a condition. Parameters are still exported as environment variables for sh steps too, but in the Jenkinsfile always use params.NAME.
For now we will only show the values in the console: the Tests stage will still always run. Making it depend on params.RUN_TESTS is the job of the when directive, in the next lesson.
The First-Run Catch
Parameters declared in the Jenkinsfile do not exist for Jenkins until the Jenkinsfile runs. The practical consequence:
- You push the
Jenkinsfilewithparameters. The job page still shows Build Now, not Build with Parameters: Jenkins has not read the file yet. - You start the build with Build Now. It runs with the default values and, when it processes the directive, Jenkins registers the parameters in the job configuration.
- From that moment on, Build with Parameters appears.
The same happens when you change or remove a parameter: the change takes effect when the modified Jenkinsfile runs. And if someone edits the parameters from Configure, their changes are overwritten on the next build: the source of truth is the Jenkinsfile.
The triggers Directive
triggers declares the automatic triggers, just like the Triggers section of the Freestyle job:
cron('...'): equivalent to Build periodically. It uses exactly the cron syntax from 02-03, withHand a time zone.\nis a line break inside the string. This is how you write the two lines you entered separately in the form:TZ=Europe/MadridandH 2 * * 1-5. Groovy interprets\ninside single quotes too.pollSCM('...'): equivalent to Poll SCM. It polls the repository configured in the job (the same one theJenkinsfileis read from) and starts a build only if there are new commits.- There is also
upstream(upstreamProjects: 'other-job', threshold: hudson.model.Result.SUCCESS), equivalent to Build after other projects are built.
If you prefer not to use \n, the alternative is a multi-line string:
It works the same, but it breaks the file's indentation; at TecnoShop we prefer \n.
Like parameters, triggers are registered when the Jenkinsfile runs: until the first build after the push, Jenkins does not know about them. And if you delete them from the Jenkinsfile, they stop applying after the next build. Webhooks, the recommended alternative to polling, arrive in 06-01.
The tools Directive
tools asks Jenkins to make a tool installed and configured by the administrator available to the steps, by adding it to the PATH:
maven 'maven-3.9': the name is not a version, but the name the administrator gave to a Maven installation in Manage Jenkins → Tools (formerly called Global Tool Configuration). If there is no installation with that name, the build fails at startup.jdk 'jdk-21': the same for the JDK.- In Manage Jenkins → Tools, the administrator can point to a path already installed on the nodes or ask Jenkins to download and install the tool automatically the first time it is needed.
Why does TecnoShop not use tools for Maven?
tools { maven '...' } |
Maven Wrapper (./mvnw) |
|
|---|---|---|
| Where the Maven version is defined | In the Jenkins configuration | In the repository (.mvn/wrapper/maven-wrapper.properties) |
| Same version locally and in Jenkins? | Only if someone keeps it in sync by hand | Always |
| Changing versions | An administrator changes Jenkins | A commit, reviewed like any other |
| Depends on the Jenkins configuration | Yes | No |
The wrapper is consistent with the pipeline as code principle: everything needed to build is in the repository. JDK 21 is provided by the node itself (today, the jenkins/jenkins:lts-jdk21 image; later, the agent). tools is still useful for tools without a wrapper or in installations with several JDKs.
The input and when Directives: Where They Go
Two directives can only go inside a stage:
whendecides whether the stage runs. It is the foundation of flow control and is covered in Flow Control.inputpauses the stage and waits for a person to confirm before continuing:
stage('Confirm') {
input {
message 'Continue with packaging?'
ok 'Continue'
}
steps {
echo 'Confirmed'
}
}message: the text the person who must confirm will see, on the build page and in the console.ok: the text of the accept button. A button to abort the build also appears.
Do not add input to the orders-api Jenkinsfile: a build waiting for confirmation blocks automatic builds and, with agent any at pipeline level, keeps an executor busy while it waits. Well-designed manual approvals (who can approve, how long to wait, without holding executors) are covered in Setting Up a CD Pipeline.
Placement and Ordering Rules
| Element | In pipeline |
In stage |
Notes |
|---|---|---|---|
agent |
Yes (required) | Yes | agent none at the root forces you to declare it in every stage |
environment |
Yes | Yes | At stage level, only visible within that stage |
options |
Yes | Yes (subset) | In a stage: timeout, retry, timestamps, skipDefaultCheckout |
parameters |
Yes | No | Only once per pipeline |
triggers |
Yes | No | Only once per pipeline |
tools |
Yes | Yes | |
input |
No | Yes | |
when |
No | Yes | |
stages |
Yes (required) | Yes (nested stages) | |
steps |
No | Yes | Required in a normal stage |
post |
Yes | Yes | Always at the end of its block |
About ordering:
- Each directive can appear only once in its block (you cannot have two
optionsblocks in the samepipeline). - Jenkins is lenient about the order in which you write the directives, but always follow the conventional order of the skeleton at the start of this lesson (
agent,environment,options,parameters,triggers,tools,stages,post). It is the order the Directive Generator produces and the one anyone reading yourJenkinsfilewill expect. - Inside a stage, the usual order is
agent,environment,tools,input,options,when,stepsandpost.
You do not need to memorize the syntax of every directive: Jenkins includes a Declarative Directive Generator that produces it from a form. You will use it in Developing and Debugging Pipelines.
Migrating the Freestyle Job to the Jenkinsfile
Laura takes stock of what orders-api-build has in the interface and where each item goes:
In orders-api-build (interface) |
In the Jenkinsfile |
|---|---|
Boolean parameter RUN_TESTS |
booleanParam(name: 'RUN_TESTS', ...) |
Choice parameter ENVIRONMENT |
choice(name: 'ENVIRONMENT', ...) |
Build periodically TZ=Europe/Madrid + H 2 * * 1-5 |
cron('TZ=Europe/Madrid\nH 2 * * 1-5') |
Poll SCM TZ=Europe/Madrid + H/15 * * * * |
pollSCM('TZ=Europe/Madrid\nH/15 * * * *') |
| 15-minute timeout | Global timeout(time: 20, unit: 'MINUTES') and 10 minutes in Tests |
| Add timestamps to the Console Output | timestamps() |
| Discard old builds | buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5')) |
| Archive the artifacts | archiveArtifacts (already migrated in 03-03) |
| Clean before checkout | Maven clean (already migrated in 03-03) |
Two of Laura's decisions deserve an explanation:
- A 20-minute timeout: the pipeline invokes Maven several times (compile, test, package, work out the version), so it gets a bit more leeway than the Freestyle job, but the
Testsstage, the one most likely to hang, gets its own tighter limit. - 30 builds: with polling and the nightly build, that is several weeks of history, enough to investigate regressions; of those, only the 5 most recent keep the jar, to protect the disk.
TecnoShop's Updated Jenkinsfile
pipeline {
agent any
options {
timestamps()
timeout(time: 20, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5'))
disableConcurrentBuilds()
}
parameters {
booleanParam(name: 'RUN_TESTS', defaultValue: true,
description: 'Uncheck only to quickly verify that the code compiles. Never for a build that is going to be deployed.')
choice(name: 'ENVIRONMENT', choices: ['dev', 'staging', 'production'],
description: 'Target environment. Informational only for now.')
}
triggers {
cron('TZ=Europe/Madrid\nH 2 * * 1-5')
pollSCM('TZ=Europe/Madrid\nH/15 * * * *')
}
stages {
stage('Build') {
steps {
echo "Build ${env.BUILD_NUMBER} of ${env.JOB_NAME} | ENVIRONMENT=${params.ENVIRONMENT} | RUN_TESTS=${params.RUN_TESTS}"
sh './mvnw -B clean compile'
}
}
stage('Tests') {
options {
timeout(time: 10, unit: 'MINUTES')
}
steps {
sh './mvnw -B test'
}
}
stage('Package') {
steps {
sh './mvnw -B -DskipTests package'
script {
def version = sh(
script: './mvnw -q help:evaluate -Dexpression=project.version -DforceStdout',
returnStdout: true
).trim()
currentBuild.description = "orders-api ${version}"
}
archiveArtifacts artifacts: 'target/*.jar', fingerprint: true
}
}
}
}What is new compared with 03-03:
- A global
optionsblock with timestamps, timeout, retention and non-concurrent builds. parametersandtriggersblocks with what used to live in the Freestyle job's interface.- The
echoinBuildnow also shows the parameters, using double quotes to interpolateparams.ENVIRONMENTandparams.RUN_TESTS. - Stage-level
optionsinTests.
Commit ("Migrate parameters, triggers and options from the Freestyle job to the Jenkinsfile"), push and click Build Now. Then check:
- The console has timestamps and the first line of
BuildshowsENVIRONMENT=dev | RUN_TESTS=true. - The job page now shows Build with Parameters.
- In Configure, the General section shows This project is parameterized and Discard old builds checked, and Triggers shows Build periodically and Poll SCM with the values from the
Jenkinsfile. Do not edit them there: they would be overwritten on the next build.
Finally, to avoid duplicate builds, disable the Freestyle job's triggers: in the Configure page of orders-api-build, uncheck Build periodically and Poll SCM and save. The Freestyle job remains as a reference that can be run by hand; the pipeline is now what builds orders-api automatically.
Common Mistakes and Tips
- Build with Parameters does not appear after the push: that is normal. Start a build with Build Now so that Jenkins registers the parameters.
- Editing parameters or triggers in Configure: the next build overwrites them with whatever the
Jenkinsfilesays. numToKeepStr: 30without quotes: these fields expect a string. Write'30'.- Using
agent { label 'linux' }before that agent exists: the build sits in the queue indefinitely. - Putting
parametersortriggersinside astage: a validation error at startup. They only go atpipelinelevel. - Duplicating directives (two
optionsblocks): a validation error. Gather all the options into a single block. - Comparing
params.RUN_TESTS == 'true': inparamsit is a boolean, not a string; that comparison is always false. - Forgetting to disable the Freestyle job's triggers: every commit would start two
orders-apibuilds. - Tip: always write a
descriptionfor your parameters. It is the only documentation anyone using Build with Parameters will see.
Exercises
Exercise 1. Point out what is wrong with this snippet and fix it:
pipeline {
agent any
stages {
stage('Build') {
parameters {
string(name: 'BRANCH', defaultValue: 'main')
}
options {
buildDiscarder(logRotator(numToKeepStr: '10'))
}
steps {
sh './mvnw -B clean compile'
}
}
}
}Exercise 2. Add a string parameter NOTE (empty by default) to the Jenkinsfile and show it in the Build console. Start a build with a note and check that it appears. Explain what you will see in the first build after the push. Remove the parameter when you are done.
Exercise 3. In addition to the weekday nightly build, Laura wants a build on Saturdays at any time between 6:00 and 11:59 (Madrid time). Write the complete triggers directive.
Solutions
Solution 1. There are two mistakes: parameters can only go at pipeline level, and buildDiscarder is a job management option that cannot go in a stage either. Jenkins would reject the Jenkinsfile at startup with validation errors. Fixed:
pipeline {
agent any
options {
buildDiscarder(logRotator(numToKeepStr: '10'))
}
parameters {
string(name: 'BRANCH', defaultValue: 'main', description: 'Branch to build')
}
stages {
stage('Build') {
steps {
sh './mvnw -B clean compile'
}
}
}
}Solution 2. In parameters, add:
And in Build:
In the first build after the push, started with Build Now or by polling, Jenkins does not ask you for the note: the build runs with the default value (empty) and the console shows Build note: . It is in that build that Jenkins registers the new parameter; in the following ones, Build with Parameters already shows the NOTE field. When you remove it from the Jenkinsfile, it will disappear from the form after the next build.
Solution 3.
triggers {
cron('TZ=Europe/Madrid\nH 2 * * 1-5\nH H(6-11) * * 6')
pollSCM('TZ=Europe/Madrid\nH/15 * * * *')
}The cron string accepts several schedule lines separated by \n; TZ on the first line applies to all the following ones. H H(6-11) * * 6 means "a minute and an hour computed between 6 and 11, on Saturdays", as you saw in 02-03.
Conclusion
You now know the complete anatomy of a declarative pipeline: the sections (pipeline, agent, stages, stage, steps and post) and the directives (environment, options, parameters, triggers, tools, input and when), where each one can go and in what order they are written. You have seen the variants of agent and why TecnoShop is sticking with agent any for now, the most useful options at pipeline and stage level, how parameters are declared and read with params along with the first-run catch, how triggers are expressed with cron and pollSCM, and why the Maven wrapper is preferable to tools. With all of this, the orders-api Jenkinsfile now covers what the Freestyle job had in the interface, and the Freestyle job's triggers are disabled. But the parameters do not decide anything yet: RUN_TESTS does not skip the tests, ENVIRONMENT is purely informational, and the pipeline does not react in any special way when something fails. You will solve this with when, post and the error handling tools in Flow Control: when, post and Error Handling.
