Chapter 10Lesson 01~110 minutes

Declarative Pipeline Syntax, agent, stages, steps, options, parameters, environment, tools, and post: Concepts, Architecture, and Mental Model

Understand Declarative Pipeline as a validated model layered on Jenkins Pipeline, with explicit directive scopes, agent allocation, environment/tool boundaries, post conditions, and evidence.

Declarative PipelineSyntax modelScopesAgentsEnvironmentPost

Learning objectives

  • Explain how a Declarative Jenkinsfile is parsed into a validated model before normal Pipeline execution.
  • Place agent, stages, steps, options, parameters, environment, tools, when, and post in their valid scopes.
  • Predict when an executor/workspace is allocated for top-level and stage-level agents.
  • Separate parameters from environment variables and secrets from ordinary configuration values.
  • Use validation/build/stage evidence to distinguish syntax/model errors from runtime failures.

1. Why Declarative Pipeline exists

Chapter 09 established that Pipeline is persisted controller-orchestrated program state whose node-bound steps execute on agents. Declarative Pipeline adds a constrained grammar on top of that engine. The constraint is useful: Jenkins can reject many structural mistakes before expensive work starts, the file communicates intent consistently, and common concerns such as agents, parameters, environment, tools, options, conditions, and post-build behavior have predictable places.

Declarative is not a different scheduler and it is not “YAML for Jenkins.” It still produces a Pipeline run, queues agent work, uses workspaces, calls Pipeline steps, and persists run state. What changes is how the Jenkinsfile expresses that program.

Key distinction: model validation can prove that a Jenkinsfile obeys Declarative grammar. It cannot prove that an agent exists, a tool is installed correctly, a credential is authorized, tests pass, or an external service is healthy.

2. Mental model: Jenkinsfile → model → execution → evidence

A Declarative Jenkinsfile is first interpreted as a structured model. Top-level sections and directives establish execution policy. Agent allocation creates an execution context when required. Stages then run steps, and post conditions react to resulting status.

Declarative causality
flowchart TD
 A[Declarative Jenkinsfile at exact SCM SHA] --> B[Parse + Declarative model validation]
 B --> C[Top-level directives]
 C --> D{Agent policy}
 D -->|top-level agent| E[Queue + executor + workspace]
 D -->|agent none| F[No global executor]
 E --> G[Stages]
 F --> G
 G --> H[Stage directives: agent / when / options / environment / tools]
 H --> I[Steps]
 I --> J[Stage result]
 J --> K[Stage / pipeline post conditions]
 K --> L[Build result + retained evidence]

Every arrow represents a state transition you can observe: source revision, validation outcome, queue item, node/workspace, stage status, console log, archived artifact, and final run result.

3. The smallest valid Declarative shape

pipeline {
  agent { label 'lab-linux' }
  stages {
    stage('Observe') {
      steps {
        echo "build=${env.BUILD_NUMBER} node=${env.NODE_NAME}"
      }
    }
  }
}

The outer pipeline block identifies Declarative syntax. A top-level agent says where stages without their own agent execute. stages contains one or more stage blocks, and a stage normally contains steps. The echo call is a Pipeline step; it is not a Declarative directive.

4. Scope is part of the language

Construct Typical valid scope What it controls Common mistake
agent Pipeline or stage Where executor/workspace-backed work runs. Assuming agent none means stages automatically find agents.
stages Inside pipeline; also sequential stages in a stage Delivery structure. Putting ordinary steps directly inside stages.
steps Inside a stage Pipeline operations. Putting directives such as parameters inside it.
options Pipeline or stage, with option availability depending on scope Run/stage policy such as timeout, retry, timestamps. Assuming top-level and stage timeout start at the same lifecycle point.
parameters Once at top level User/build inputs exposed through params and exported values. Treating free-form input as trusted shell syntax.
environment Pipeline or stage Environment values for enclosed steps. Using it as a general-purpose secret vault.
tools Pipeline or stage Configured JDK/Maven/Gradle tools placed on execution path. Expecting it to work without an agent/tool definition.
when Stage Whether a stage should execute. Confusing skipped stage with failed execution.
post Pipeline or stage Conditional cleanup/evidence/notification after status is known. Assuming a workspace always exists.

5. Top-level versus stage-level agents

A top-level agent is simple: Jenkins allocates one executor/workspace and normally keeps it for the Pipeline's stages. With agent none, no executor is reserved globally; each stage that needs a workspace must declare an agent. This can reduce idle executor time and lets stages use different labels or toolchains.

pipeline {
  agent none
  stages {
    stage('Build') {
      agent { label 'lab-linux' }
      steps { sh 'printf "build on %s\\n" "$NODE_NAME"' }
    }
    stage('Review') {
      // A stage can use an input directive before acquiring an agent.
      input { message 'Continue the disposable lab?' }
      agent { label 'lab-linux' }
      steps { echo 'Approved; agent acquired for work.' }
    }
  }
}

The stage-level input directive pauses before that stage enters its agent, which avoids holding an executor during human waiting. By contrast, an input step placed inside steps executes after the stage agent is allocated and can hold capacity while waiting.

6. Parameters, environment, and credentials are different state

A parameter is a build input. An environment variable is a process-facing value constructed for enclosed steps. A Jenkins credential is protected controller configuration that should be bound only at the narrowest required scope. Declarative's environment supports a credentials() helper for supported credential types, but convenience does not turn console masking into a complete confidentiality boundary.

parameters {
  choice(name: 'TARGET', choices: ['sandbox', 'qa'], description: 'Lab target')
  booleanParam(name: 'RUN_TESTS', defaultValue: true, description: 'Run tests')
}
environment {
  APP_NAME = 'declarative-lab'
}

Validate untrusted parameter values before passing them to shells or external APIs. Do not echo credentials, interpolate secrets into Groovy strings, or let a free-form parameter select arbitrary production resources.

7. Tool directives name controller configuration; agents supply execution

The current Declarative reference documents built-in tools support for Maven, JDK, and Gradle. The name must already exist under Jenkins tool configuration. The directive adds the selected installation to the execution environment; it does not mean the controller JVM itself switches Java versions.

tools {
  jdk 'jdk21-build'
  maven 'maven-3.9'
}

If top-level agent none is used, a top-level tool definition has no global execution context to act upon; prefer stage-local tools next to the stage agent that uses them.

8. post is conditional follow-up, not magic rollback

post can run conditions such as always, success, failure, unstable, changed, unsuccessful, and cleanup. Use it for evidence retention and bounded cleanup. Do not assume a failed external deployment can be undone merely because a post { failure { ... } } block runs.

post {
  always {
    echo "finalResult=${currentBuild.currentResult}"
  }
  cleanup {
    echo 'Run cleanup after other post conditions.'
  }
}

9. Read-only inspection before editing

  • Record Jenkins core, Java, Pipeline and Declarative plugin versions.
  • Record the job full name, build number/URL, cause, and exact Jenkinsfile/source SHA.
  • Inspect the current Jenkinsfile for directive placement before changing it.
  • Record current node labels and configured tool names.
  • Inspect stage results and console output from the last known build.
  • Record credential IDs only—not secret values—if the Pipeline binds credentials.

This establishes a baseline so a later validation error, queue wait, tool-resolution error, or post failure can be assigned to the correct layer.

10. Four misconceptions to remove now

Misconception Correction
“If Declarative validates, the build will succeed.” Validation proves structure, not runtime resources or business correctness.
“Every stage needs a new agent.” A top-level agent can be reused; stage agents are a design choice.
“Environment variables are safe places for secrets.” Environment exposure and masking have limits; bind secrets narrowly and avoid logging them.
“post always has the same workspace.” Workspace availability depends on agent design and failure state; make evidence/cleanup requirements explicit.
Next lesson

Guided Hands-On Workflow and Core Operations

Build a Declarative Jenkinsfile incrementally, validate each structural change, add scoped agents/tools/options/parameters/environment/post, and deliberately repair a model error.

Knowledge check

What does Declarative model validation prove?

Why can agent none reduce wasted capacity?

Where may parameters appear?

Why is a stage-level input directive different from an input step inside steps?

Does a post failure block automatically roll back an external deployment?

Official references and version notes

Version and compatibility note

Rechecked on 2026-09-16. Examples assume Jenkins 2.568.3 LTS, tested with Java 21 and 25, Pipeline aggregator 608.v67378e9d3db_1, Pipeline: Declarative 2.2293.v6e7193cec599, Credentials Binding 728.v902a_273b_8947, and optional Stage View 2.41. Declarative 2.2293 requires Jenkins 2.504.3 or newer. Labs reuse the Chapter 08 tool names jdk21-build and maven-3.9; verify what exact binaries those names resolve to on your disposable agent before running. Plugin versions and supported directives change independently, so capture the installed baseline rather than assuming these versions forever.

Keep the academy open

Support free, practical DevOps education.

Every lesson is designed to remain readable in a browser, downloadable from GitHub, and usable without a paid learning platform. Contributions help expand and maintain the curriculum.

Ethereum / ERC-20
0x716c4Ab160C4B66F31a28AE2448BfF68fc3a2ef0Send only Ethereum/ERC-20 compatible assets to this address.