Pipelines and Pipeline as Code
What this domain covers
The heaviest domain by question weight. You must read and write both syntaxes, know the declarative directive set, and understand shared libraries, sandboxing, and durability.
Core rules
- Two syntaxes. Scripted pipeline is Groovy:
node { stage('Build') { sh 'make' } }. Declarative pipeline has a fixed shape:pipeline { agent any; stages { stage('x') { steps { … } } }; post { … } }. Declarative is a DSL; Groovy-only logic goes insidescript { }. - Directives:
agent,environment,options,parameters,triggers,tools,stages,post,when,input,matrix,libraries.agent noneat the top lets each stage pick its own agent. postconditions:always,success,failure,unstable,aborted,changed,fixed,regression,unsuccessful,cleanup.cleanupruns last - the right place forcleanWs().whenconditions:branch,tag,buildingTag,changeRequest,changeset,changelog,environment,equals,expression,triggeredBy,not/allOf/anyOf, plus the modifiersbeforeAgent,beforeInput,beforeOptions.options:buildDiscarder(logRotator(numToKeepStr:'20')),timeout(time:30, unit:'MINUTES'),retry(3),timestamps(),disableConcurrentBuilds(),skipDefaultCheckout(),skipStagesAfterUnstable(),parallelsAlwaysFailFast(),durabilityHint('PERFORMANCE_OPTIMIZED').- Durability. The default
PERFORMANCE_OPTIMIZEDpersists pipeline state after each step so a restart can resume;MAX_SURVIVABILITYwrites more often,NONEleast. - Shared libraries. Configure under Manage Jenkins → System → Global Pipeline Libraries, then
@Library('ci-lib@main') _in scripted orlibraries { lib('ci-lib') }in declarative. Layout:vars/for global steps (vars/buildApp.groovy),src/for classes,resources/forlibraryResource. Trusted libraries run outside the sandbox.
Worked example
A release stage must run only for tag builds and must fail fast on a failing smoke test. Put options { timeout(time: 15, unit: 'MINUTES') } at pipeline level and when { buildingTag() } on the stage. Reasoning: buildingTag() is true when the build was caused by a tag, whereas tag 'v*' pattern-matches the tag name - different conditions. A failing sh aborts the stage and triggers post { failure { … } }.
Traps
Putting node inside declarative steps; using return instead of returnStatus: true to capture an exit code; assuming Replay persists (edits vanish unless committed); expecting post { failure } to fire for aborted builds; stepping outside the sandbox inside script blocks and then hitting script approval.