Jenkins

Jenkinsfile Generator: CI/CD Pipelines from Zero

Beginner
15 minutes
Updated October 2026

Understand Jenkinsfile syntax and structure from scratch — declarative pipelines, stages, agents, and real examples you can copy. By the end you'll be able to write a production-grade pipeline without copy-pasting one you half-understand.

Table of Contents

Declarative vs Scripted

Two Jenkinsfile syntaxes:

DeclarativeScripted
SyntaxStructured, opinionatedRaw Groovy
Learning curveEasyHard
Flexibility90% of use casesFull control
Error messagesClear ("expected X")Groovy stack traces
RecommendationStart hereOnly if needed

This guide uses Declarative — it's what most teams use, what the docs lead with, and what every example online assumes. Scripted pipelines can drop into Groovy for anything Declarative can't express, but that's the exception.

Pipeline Anatomy

pipeline {
    agent any                    // where it runs

    environment {                // env vars for all stages
        APP_NAME = 'my-app'
    }

    options {                    // pipeline options
        timeout(time: 30, unit: 'MINUTES')
    }

    stages {                     // the actual work
        stage('Build') {
            steps {
                sh 'make build'
            }
        }
    }

    post {                       // always runs at the end
        always {
            cleanWs()
        }
    }
}

The hierarchy is strict: pipeline contains stages, stages contains stages, each stage has steps. Every structural keyword has a fixed home — you can't nest stage inside steps, which is the syntax error beginners hit most.

Essential Directives

agent — Where Stages Run

agent any                                    // any available agent
agent none                                   // set per-stage instead
agent { label 'docker' }                     // agent with a label
agent {
    docker {                                 // inside a container
        image 'node:20-alpine'
        args '-v /cache:/cache'
    }
}
agent {
    kubernetes {                             // K8s pod agent
        yaml '''
          spec:
            containers:
            - name: node
              image: node:20
        '''
    }
}

agent any is fine to start; agent { docker ... } is the upgrade that matters — every build gets a clean container with exactly the toolchain you pinned, no "it works on the Jenkins box" drift.

environment — Variables

environment {
    NODE_ENV = 'production'
    CREDS = credentials('my-secret-id')     // auto-injects CREDS_USR / CREDS_PSW
}

credentials('id') is how secrets enter a pipeline safely — bound from the credential store, masked in logs, never written to the Jenkinsfile. CREDS_USR/CREDS_PSW are the auto-generated username/password splits.

parameters — User Input

parameters {
    string(name: 'VERSION', defaultValue: '1.0.0')
    choice(name: 'ENV', choices: ['dev', 'staging', 'prod'])
    booleanParam(name: 'DEPLOY', defaultValue: false)
}
// Access via params.ENV

Parameters turn a pipeline into a self-service tool — a DEPLOY checkbox plus ENV dropdown is how you let non-Jenkins people trigger controlled releases.

when — Conditional Stages

stage('Deploy') {
    when {
        allOf {
            branch 'main'
            expression { params.DEPLOY }
        }
    }
    steps { sh './deploy.sh' }
}

when supports branch, tag, changeset (files changed), expression (arbitrary Groovy), and combinators allOf/anyOf/not. changeset is the monorepo trick — run the frontend tests only when frontend/** changed.

post — After Pipeline

post {
    always  { echo 'runs regardless' }
    success { echo 'only on success' }
    failure { echo 'only on failure' }
    cleanup { cleanWs() }              // runs last, always
}

cleanup runs after everything — the right place for cleanWs() so failed builds don't leave gigabytes of workspace on the agent.

Options: the directives people skip

options is where production pipelines live:

options {
    timeout(time: 30, unit: 'MINUTES')          // kill hung builds
    disableConcurrentBuilds()                    // one deploy at a time
    buildDiscarder(logRotator(numToKeepStr: '20')) // cap build history
    retry(2)                                     // retry whole pipeline
    timestamps()                                 // wall-clock on every log line
    skipDefaultCheckout()                        // control checkout yourself
}

timeout and disableConcurrentBuilds are the two that prevent real incidents — a hung build squatting on an agent forever, and two deploys racing production.

Complete Examples

Minimal Node.js App

pipeline {
    agent {
        docker { image 'node:20-alpine' }
    }
    stages {
        stage('Install') {
            steps { sh 'npm ci' }
        }
        stage('Test') {
            steps { sh 'npm test' }
        }
        stage('Build') {
            steps { sh 'npm run build' }
        }
    }
}

Parallel Stages

stage('Checks') {
    parallel {
        stage('Lint')    { steps { sh 'npm run lint' } }
        stage('Types')   { steps { sh 'npm run typecheck' } }
        stage('Tests')   { steps { sh 'npm test' } }
    }
}

Parallel stages are the biggest free speedup — three independent checks in one stage wall-clock time instead of three sequential waits.

Multi-Environment Deploy

stage('Deploy Dev') {
    when { branch 'develop' }
    steps { sh './deploy.sh dev' }
}
stage('Deploy Prod') {
    when { branch 'main' }
    input { message 'Deploy to production?' ok 'Deploy' }
    steps { sh './deploy.sh prod' }
}

input pauses the pipeline for human approval — the manual gate before prod. The build waits (with a URL to approve) rather than failing; the timeout in options is what keeps a forgotten approval from waiting forever.

Credentials Handling

stage('Push') {
    steps {
        withCredentials([usernamePassword(
            credentialsId: 'registry-creds',
            usernameVariable: 'REG_USER',
            passwordVariable: 'REG_PASS'
        )]) {
            sh 'echo $REG_PASS | docker login -u $REG_USER --password-stdin'
        }
    }
}

withCredentials scopes the secret to just the block that needs it — the variable doesn't exist outside the braces, so it can't leak into a later sh or get archived by accident.

Common Patterns

Retry on Flaky Steps

steps {
    retry(3) {
        sh 'npm ci'   // network flakiness
    }
}

Save Artifacts

post {
    always {
        archiveArtifacts artifacts: 'dist/**', fingerprint: true
        junit 'reports/**/*.xml'
    }
}

archiveArtifacts keeps build outputs downloadable from the Jenkins UI; junit parses test reports into the per-build test result graph — the difference between "tests failed" and "these 3 tests failed, here's the trend."

Shared Stash Between Stages

stage('Build') {
    steps {
        sh 'npm run build'
        stash includes: 'dist/**', name: 'built'
    }
}
stage('Deploy') {
    steps {
        unstash 'built'
        sh './deploy.sh'
    }
}

stash/unstash moves files between stages that might run on different agents — the workaround for the fact that each stage's workspace isn't guaranteed to be the same filesystem.

Debugging Pipelines

Check Syntax Before Committing

# Jenkins validates Jenkinsfile via HTTP API
curl -X POST -F "jenkinsfile=<Jenkinsfile" \
  "$JENKINS_URL/pipeline-model-converter/validate"

Blue Ocean / Pipeline Steps View

Click a failing build → see exactly which stage/step failed with timing per stage. The classic UI's "Pipeline Steps" view does the same job.

Replay a Build

Jenkins → failed build → Replay — edit the Jenkinsfile inline and re-run without pushing a commit. The single biggest time-saver for pipeline debugging: iterate on the Groovy directly instead of commit-push-wait-fail cycles.

Common Errors

ErrorCause
No such DSL methodTypo in directive, or missing plugin
WorkflowScript missingSyntax error at top level
agent none + no stage agentEvery stage needs its own agent
Scripts not permittedNeeds script approval (admin) — Groovy sandbox blocked it
Written & Reviewed by Yasir Masood, CloudOpsGuide Editor

Our tutorials and troubleshooting runbooks are written by a DevOps practitioner with hands-on experience operating Kubernetes, Terraform, CI/CD pipelines, and Linux infrastructure in production. Commands, manifests, and configurations are verified against current tooling releases. Learn more about our editorial process or report a correction or outdated flag.