How to Write a Declarative Jenkinsfile
A declarative Jenkinsfile wraps everything in a pipeline {} block with a required agent and stages, giving a structured, readable pipeline.
Start every declarative pipeline with pipeline {}, declare where it runs via agent, and list ordered work under stages. This is the recommended modern syntax.
Minimal declarative pipeline
The agent any runs on any available node; each stage groups related steps.
Jenkinsfile
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'npm ci && npm run build'
}
}
stage('Test') {
steps {
sh 'npm test'
}
}
}
}Gotchas
pipeline,agent, andstagesare all required; omittingagentfails validation.- Declarative is structured and validated; scripted (
node {}) is raw Groovy with no schema. Prefer declarative. - Drop into raw Groovy inside a
script {}block when you need logic declarative does not support.
Key takeaways
- Every declarative pipeline needs
pipeline,agent, andstages. - Declarative is validated; scripted Groovy is not.
- Use
script {}to embed Groovy when needed.
Related guides
How to Use Stages and Steps in a Jenkins PipelineUse stages and steps in a Jenkins declarative pipeline to structure work into visible phases, each containing…
How to Target Agents by Label in a Jenkins PipelineTarget Jenkins agents by label with agent { label }, pin stages to specific nodes, and run stages inside Dock…