The Jenkinsfile you pushed to orders-api in the previous lesson starts with pipeline {. That first word is no accident: it tells you the file is written in declarative syntax. Jenkins supports a second style, the scripted syntax, which starts with node { and which you will come across in many older projects, in forum answers and in the documentation of some plugins. Both styles run on the same engine, but they follow different philosophies: one describes what should happen using a fixed structure; the other is a Groovy program with all the freedom that implies. In this lesson you will write the same orders-api pipeline in both styles, compare them point by point, understand what lies underneath (Groovy, the CPS engine and the sandbox), learn to use the script { } block as a bridge between the two worlds and see why TecnoShop adopts declarative as its standard.
Two Styles, One Engine
Jenkins pipelines first appeared in scripted syntax: a Jenkinsfile was simply a Groovy program that called steps such as node, stage or sh. It was very powerful, but it required programming skills, every team structured its pipelines its own way and errors showed up halfway through execution. Years later came the declarative syntax, which imposes a fixed structure (pipeline, agent, stages, stage, steps...) that is easier to read, validate and visualize.
flowchart TB
D["Declarative Jenkinsfile<br/>pipeline { ... }"] --> M["Declarative model:<br/>validates the structure"]
M --> G["Transformed Groovy (CPS)"]
S["Scripted Jenkinsfile<br/>node { ... }"] --> G
G --> E["Pipeline execution engine<br/>(same steps: sh, echo, archiveArtifacts...)"]
The key point of the diagram: declarative is built on top of scripted. Both end up running on the same engine and use exactly the same steps (sh, echo, archiveArtifacts...). What changes is the structure around them and the guarantees it provides.
The orders-api Pipeline in Declarative Syntax
This is the current orders-api Jenkinsfile, just as you left it in Pipeline as Code:
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'chmod +x mvnw'
sh './mvnw -B -DskipTests package'
}
}
stage('Tests') {
steps {
sh './mvnw -B test'
}
}
}
}Features of the declarative syntax:
- Everything goes inside a top-level
pipeline { }block. - Sections have fixed names and positions:
agentcomes beforestages; insidestagesthere can only bestageblocks; inside eachstage, the steps go insteps. - There is no visible programming logic: no variables, no
if, no loops. Decisions are expressed with directives such aswhen, which you will see in Flow Control. - The code checkout is implicit (
Declarative: Checkout SCM).
The Same Pipeline in Scripted Syntax
This is what the same pipeline would look like in scripted syntax:
node {
stage('Checkout') {
checkout scm
}
stage('Build') {
sh 'chmod +x mvnw'
sh './mvnw -B -DskipTests package'
}
stage('Tests') {
sh './mvnw -B test'
}
}Line by line:
node { ... }: requests an executor on any available node and creates a workspace. Everything inside it runs there. It is the equivalent ofagent any. With a label it would benode('linux') { ... }.stage('Checkout') { ... }: defines a stage. In scripted syntax,stageis simply a step that groups other steps and gives them a name for the stage view. There is nostepsblock: the steps go directly inside.checkout scm: scripted syntax has no implicit checkout. If you forget it, the workspace will be empty and./mvnwwill fail withnot found.- The rest are the same
shsteps as in the declarative version.
At first glance, the scripted version is even shorter. The difference shows up when the pipeline grows and when something fails.
Side-by-Side Comparison
| Concept | Declarative | Scripted |
|---|---|---|
| Root block | pipeline { } |
None required; usually node { } |
| Where it runs | agent any |
node { } |
| Stages | stages { stage('X') { steps { ... } } } |
stage('X') { ... } |
| Checkout | Implicit | Explicit: checkout scm |
| Condition | when { expression { ... } } |
if (...) { ... } |
| Final actions (always, on failure...) | post { always {...} failure {...} } section |
try { ... } catch (e) { ... } finally { ... } |
| Variables | environment directive or script block |
def version = ... anywhere |
| Parameters and triggers | parameters, triggers directives |
properties([...]) step |
To see the difference in a more realistic case, compare how you write "show a warning if the build fails and, in any case, a final message" in each style:
// Declarative
pipeline {
agent any
stages {
stage('Tests') {
steps {
sh './mvnw -B test'
}
}
}
post {
failure {
echo 'The tests failed'
}
always {
echo 'End of build'
}
}
}// Scripted
node {
try {
stage('Checkout') {
checkout scm
}
stage('Tests') {
sh './mvnw -B test'
}
} catch (err) {
currentBuild.result = 'FAILURE'
echo 'The tests failed'
throw err
} finally {
echo 'End of build'
}
}In the scripted version, it is up to you to remember to catch the error, set the build result and rethrow the exception (throw err); if you forget, the build will end green even though the tests failed. In the declarative version, post takes care of everything and its intent is clear at a glance. You will study the post section in depth in Flow Control: when, post and Error Handling.
Detailed Comparison Table
| Criterion | Declarative | Scripted |
|---|---|---|
| Structure | Fixed and predictable: every declarative Jenkinsfile reads the same way |
Free-form: each author organizes it differently |
| Validation before execution | Yes: Jenkins validates the structure and step parameters before running anything | No: errors appear when execution reaches the offending line, perhaps after minutes of building |
| Learning curve | Gentle: no Groovy knowledge required | Steeper: it is Groovy programming with the quirks of the CPS engine |
| Flexibility | Limited to what its directives allow (extensible with script { }) |
Total: loops, functions, data structures, arbitrary logic |
| Restart from Stage | Yes: you can rerun a build from a specific stage | Not available |
Final actions (post) |
post section with conditions (always, failure, fixed...) |
Manual, with try/catch/finally |
| Conditions | when directive, and a skipped stage is shown as such in the view |
if; a stage that does not run simply does not appear |
| Editor and generators | Declarative Directive Generator, official linter, visual editors | Only Snippet Generator for steps |
| Visualization | Stage View and Pipeline Graph View, with skipped stages, parallel stages and post clearly represented |
Stage View and Pipeline Graph View, with less structural information |
| Error messages | Clear, with line numbers and even suggestions | Groovy exceptions, sometimes with long stack traces |
| Linter validation | Yes (03-06) | There is no equivalent validator |
The validation before execution row deserves an example. Suppose that, when adding the jar archiving, you write artifact instead of artifacts, or stpes instead of steps. In a declarative pipeline, the build fails within the first second, without compiling anything:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 5: Unknown stage section "stpes". Starting with version 0.5, steps in a stage must be in a ‘steps’ block. @ line 5, column 9.
stage('Build') {
^
WorkflowScript: 14: Invalid parameter "artifact", did you mean "artifacts"? @ line 14, column 34.startup failed: the error is detected when theJenkinsfileis compiled, before any stage runs.WorkflowScript: 5: the line number in theJenkinsfile.- Jenkins reports all the errors at once and even suggests the fix (
did you mean "artifacts"?).
In a scripted pipeline, the error in the step parameter would only appear when execution reached that line: after downloading the code, compiling and passing the tests. With a twenty-minute pipeline, the difference is huge.
What Lies Underneath: Groovy and the CPS Engine
Whether you write in declarative or scripted syntax, your Jenkinsfile is, at heart, a Groovy program. Groovy is a language for the Java platform with a lighter syntax (no semicolons needed, parentheses optional in many calls...). But it does not run like a normal Groovy program.
Why the Code Is Serialized
In Understanding Jenkins Pipelines you saw that a pipeline survives a controller restart. To achieve this, Jenkins transforms your code with a technique called CPS (Continuation-Passing Style). Put simply:
- Before running it, Jenkins rewrites your program so that, at every step, it knows "what is left to do" (the continuation).
- While it runs, it keeps saving the program state to disk: which line it is on and the values of local variables. This is called serializing.
- If the controller restarts, it reads that state from disk and carries on from where it was.
flowchart LR
A["Your Jenkinsfile<br/>(Groovy)"] --> B["CPS transformation"]
B --> C["Step-by-step execution<br/>on the controller"]
C -->|"at every step"| D["Serialized state<br/>on disk (build.xml and program.dat)"]
D -->|"after a restart"| C
Practical Consequences
This transformation comes at a price: some Groovy constructs do not behave the same as in a normal program.
- Groovy code runs on the controller, not on the agent. Only steps such as
shrun on the allocated node. For example,new File('target/orders-api-1.0.0-SNAPSHOT.jar').exists()would check the controller's disk, not the workspace (and the sandbox would block it anyway). The right way is to use steps:fileExists 'target/orders-api-1.0.0-SNAPSHOT.jar',readFile,writeFileorsh. - Objects that cannot be serialized cause trouble. If you store in a variable an object that Java cannot serialize (the classic example is a
java.util.regex.Matcher, the result of using=~) and then run a step, Jenkins tries to save the state and the build fails withjava.io.NotSerializableException. The fix is usually to extract the value you need (aString) right away and not hold on to the object. - Some Groovy collection functions and closures behave differently, or with limitations, inside transformed code. If a piece of "plain" Groovy behaves strangely in a
Jenkinsfile, suspect CPS. - Groovy code performance is poor, because every operation is recorded. A pipeline is not the place to process large volumes of data.
There is an annotation, @NonCPS, that marks a method to run as normal Groovy, untransformed (and therefore unable to call steps inside it). It is enough for you to know it exists; if you ever need it, it is probably time to move that logic into a shared library (04-06) or into a script run with sh.
The rule of thumb that follows from all this: the less Groovy logic in the Jenkinsfile, the better. Pipelines should orchestrate tools (./mvnw, npm, docker...), not implement complex logic. That is another argument in favor of declarative.
The Sandbox, Once Again
Because Groovy code runs inside the controller, with potential access to all of Jenkins, a Jenkinsfile loaded from the repository always runs in the sandbox: it can only call pipeline steps and methods included in an allowlist. This applies equally to declarative and scripted pipelines, but in practice scripted pipelines, since they use more Groovy, run into the sandbox far more often. The typical error is a RejectedAccessException; you will learn to read it and to decide whether that method should be approved in Developing and Debugging Pipelines.
The script { } Block: A Bridge Between Both Styles
What if, in a declarative pipeline, you need a bit of logic that the directives do not cover, such as storing the output of a command in a variable? That is what the script { } block is for: you write it inside steps, and it lets you include code in scripted syntax.
A useful case for TecnoShop: finding out the project version declared in pom.xml (1.0.0-SNAPSHOT) and showing it in the build description, so that Build History shows which version each build produced. Maven can print that version with the help plugin:
-q(quiet): suppresses Maven's messages ([INFO] ...), so that the output is just the value.help:evaluate: theevaluategoal of thehelpplugin computes an expression from the project model.-Dexpression=project.version: the expression to evaluate, the project version.-DforceStdout: writes the result to standard output, with nothing else around it.
Try it on your computer: it should print 1.0.0-SNAPSHOT.
Now, in the Jenkinsfile, add a script block at the end of the Build stage:
stage('Build') {
steps {
sh 'chmod +x mvnw'
sh './mvnw -B -DskipTests package'
script {
def version = sh(
script: './mvnw -q help:evaluate -Dexpression=project.version -DforceStdout',
returnStdout: true
).trim()
echo "Project version: ${version}"
currentBuild.description = "orders-api ${version}"
}
}
}Let's go through it carefully, because it contains several new ideas:
script { ... }: opens a block of scripted code. It can only go insidesteps.def version = ...: declares a local variable calledversion. You could not do this in the declarative part; insidescript, you can.sh(script: '...', returnStdout: true): the same oldshstep, but with two named arguments.scriptis the command, andreturnStdout: truetells the step to return the output as text instead of showing it in the console. When you use the return value, the parentheses are mandatory..trim(): removes leading and trailing whitespace and line breaks. It is an essential habit withreturnStdout, because many commands end their output with a line break that would otherwise stick to the value.echo "Project version: ${version}": shows the value. Double quotes let you insert the variable with${...}; you will see this in detail in the next lesson.currentBuild.description = "...":currentBuildis a global variable that represents the current build. Assigning itsdescriptionmakes the text appear under the build number in Build History and on the build page.
Commit and push:
After the next build, Build History will show something like:
And in the console for the Build stage:
[Pipeline] script
[Pipeline] {
[Pipeline] sh
+ ./mvnw -q help:evaluate -Dexpression=project.version -DforceStdout
[Pipeline] echo
Project version: 1.0.0-SNAPSHOT
[Pipeline] }
[Pipeline] // scriptNotice that the output of ./mvnw does not appear in the console: returnStdout captured it and stored it in version.
Use script Sparingly
script { } is a handy escape hatch, but each block is an island of scripted code: it is not validated before it runs, and it brings back the CPS and sandbox issues. TecnoShop's recommendations:
- Use it for small pieces of logic: capturing a value, setting
currentBuild.description, a one-off condition. - If a
scriptblock grows beyond about ten lines, or is repeated across several pipelines, it is a candidate for a shared library function (04-06). - Before writing a
scriptwith anif, check whether a directive such aswhensolves the problem (03-05).
Decision Criteria and the TecnoShop Standard
| Situation | Recommended style |
|---|---|
| New build, test and deployment pipeline | Declarative |
| Team with little Groovy experience | Declarative |
You need Restart from Stage, post or linter validation |
Declarative |
| A one-off piece of logic inside a declarative pipeline | Declarative + script { } |
| Highly dynamic logic (for example, generating stages from a list computed at run time) | Scripted, or declarative backed by a shared library |
| Maintaining an old scripted pipeline that works | Keep it; migrate it when major changes are needed |
Laura writes up the team standard:
- All new TecnoShop pipelines are written in declarative syntax.
- The
script { }block is allowed for short logic; complex or repeated logic will go into thetecnoshop-libshared library, which will be created in module 4. - Stage names are in English (
'Build','Tests','Package'...).
This course follows the same approach: from here on, all examples are declarative. You will be able to read scripted syntax when you come across it, and you will use it occasionally inside script { }.
Common Mistakes and Tips
- Mixing styles without
script: writingdef version = ...or anifdirectly insidestepscauses a validation error at startup. That code must go insidescript { }. - Forgetting
checkout scmin scripted syntax: there is no implicit checkout; the workspace is empty. try/catchwithoutthrow: in scripted syntax, catching the error without rethrowing it makes a failed build end green.- Forgetting
.trim()withreturnStdout: the value carries a trailing line break that breaks comparisons and text. - Using
new File(...)or reading files with Groovy: this runs on the controller, not in the workspace. UsereadFile,fileExistsorsh. - Storing non-serializable objects in variables (such as a
Matcher):NotSerializableExceptionon the next step. - Tip: when you copy an example from the internet, look at the first line. If it starts with
node {, it is scripted and you will have to adapt it before pasting it into a declarativeJenkinsfile.
Exercises
Exercise 1. Convert this scripted pipeline, which someone found on a forum, to declarative syntax:
node {
stage('Checkout') {
checkout scm
}
stage('Info') {
sh 'java -version'
sh 'git log -1 --oneline'
}
}Exercise 2. In the script block of the Build stage, also obtain the project identifier (project.artifactId) and make the build description orders-api 1.0.0-SNAPSHOT, built from both values, without typing orders-api by hand.
Exercise 3. Diego writes this check inside a script block and is surprised that it always says the jar does not exist, even though the previous stage generated it. Explain why and fix it.
script {
if (new File('target/orders-api-1.0.0-SNAPSHOT.jar').exists()) {
echo 'The jar exists'
} else {
echo 'The jar does NOT exist'
}
}Solutions
Solution 1.
pipeline {
agent any
stages {
stage('Info') {
steps {
sh 'java -version'
sh 'git log -1 --oneline'
}
}
}
}The Checkout stage disappears because declarative syntax performs the implicit checkout (Declarative: Checkout SCM). node becomes agent any, and the Info steps go inside steps.
Solution 2.
script {
def artifactId = sh(
script: './mvnw -q help:evaluate -Dexpression=project.artifactId -DforceStdout',
returnStdout: true
).trim()
def version = sh(
script: './mvnw -q help:evaluate -Dexpression=project.version -DforceStdout',
returnStdout: true
).trim()
currentBuild.description = "${artifactId} ${version}"
}Each call returns a value that is stored in its own variable, and the description is built with a double-quoted string that interpolates both. Keep in mind that each ./mvnw call adds a few seconds to the build; for a single value it is worth it, but for many values you would need to find another approach.
Solution 3. The pipeline's Groovy code runs on the controller, and new File(...) with a relative path looks for the file in the working directory of the controller process, not in the build workspace. That is why it never finds it (besides, in the sandbox, using File would trigger a security error). The right way is to use the fileExists step, which checks the path in the workspace of the current node:
script {
if (fileExists('target/orders-api-1.0.0-SNAPSHOT.jar')) {
echo 'The jar exists'
} else {
echo 'The jar does NOT exist'
}
}Conclusion
You have seen that Jenkins supports two pipeline styles on the same engine: scripted (node { }), a Groovy program with complete freedom, and declarative (pipeline { }), a fixed structure that is validated before it runs, offers post, when and Restart from Stage, and is easier to read and maintain. You understand that underneath there is Groovy transformed by the CPS engine, which serializes state to survive restarts and imposes some limitations, and that everything runs in a sandbox. You have used script { } as a bridge to capture the project version with sh(returnStdout: true).trim() and show it in the build description, and you know the TecnoShop standard: always declarative, with script only for short logic. With the style settled, it is time to build the first "real" orders-api Jenkinsfile, one that reproduces and improves on the orders-api-build Freestyle job; you will do this step by step in Creating a Simple Pipeline.
