Skip to content
Latchkey

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, and stages are all required; omitting agent fails 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, and stages.
  • Declarative is validated; scripted Groovy is not.
  • Use script {} to embed Groovy when needed.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →