Certified Jenkins Engineer

Pipeline Structure and Scripted vs Declarative

Best Practices for Scripted Pipelines

In this lesson, we’ll cover essential recommendations to optimize your Jenkins pipelines—both scripted and declarative—and then dive into guidelines that apply specifically to scripted pipelines. Following these practices will improve performance, maintainability, and reliability across your CI/CD workflows.

Note

These general best practices apply to both Scripted and Declarative Pipelines in Jenkins.

General Best Practices

Best PracticeBenefitImplementation Example
Efficient Log ManagementReduces controller load and speeds up runsWrite build logs to a file on the agent, then compress and archive them as build artifacts via archiveArtifacts
Leverage Jenkins PluginsSimplifies maintenance and updatesUse plugins for SCM, artifact handling, deployment, and notifications instead of custom scripts
Keep Pipelines ConciseEasier to read, debug, and maintainAim for fewer than 300 steps. Consolidate related commands into external helper scripts or tools
Use Command-Line ToolsFaster data processingOffload heavy transformations or API calls to shell scripts, batch files, or CLI utilities like curl or aws CLI
Delegate to AgentsKeeps controller responsiveSchedule large data processing or long-running tasks on dedicated agent nodes
Minimize In-Pipeline LogicMaintains pipeline “glue”Avoid embedding complex Groovy expressions—use pipeline steps and external scripts for business logic

Scripted Pipeline–Specific Guidelines

  1. Stick to Basic Groovy Syntax
    Use only core Groovy features (loops, conditionals, closures). Avoid DSL meta-programming or AST transformations that make debugging difficult.

  2. Avoid Direct Jenkins API Calls

    Warning

    Do not invoke Jenkins internal APIs (e.g., hudson.model.*) from your Jenkinsfile.
    For advanced integration, develop a custom Pipeline Step Plugin instead.

  3. Prefer CLI Parsers Over Groovy Libraries
    For XML/JSON manipulation, use tools like xmllint or jq rather than in-pipeline Groovy parsing to reduce controller memory usage.

  4. Don’t Perform Raw Network or I/O Operations

    Warning

    Never fetch URLs or read/write files directly in your Jenkinsfile.
    Wrap these operations in sh, bat, or custom steps to ensure proper error handling and resource cleanup.


The image is a slide titled "Pipelines – Best Practices," listing best practices such as efficient log management and leveraging Jenkins plugins, alongside practices to avoid like complex Groovy features and network calls.

References

Watch Video

Watch video content

Practice Lab

Practice lab

Previous
Demo Scripted Pipeline K8S Agent