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 Practice | Benefit | Implementation Example |
---|---|---|
Efficient Log Management | Reduces controller load and speeds up runs | Write build logs to a file on the agent, then compress and archive them as build artifacts via archiveArtifacts |
Leverage Jenkins Plugins | Simplifies maintenance and updates | Use plugins for SCM, artifact handling, deployment, and notifications instead of custom scripts |
Keep Pipelines Concise | Easier to read, debug, and maintain | Aim for fewer than 300 steps. Consolidate related commands into external helper scripts or tools |
Use Command-Line Tools | Faster data processing | Offload heavy transformations or API calls to shell scripts, batch files, or CLI utilities like curl or aws CLI |
Delegate to Agents | Keeps controller responsive | Schedule large data processing or long-running tasks on dedicated agent nodes |
Minimize In-Pipeline Logic | Maintains pipeline “glue” | Avoid embedding complex Groovy expressions—use pipeline steps and external scripts for business logic |
Scripted Pipeline–Specific Guidelines
Stick to Basic Groovy Syntax
Use only core Groovy features (loops, conditionals, closures). Avoid DSL meta-programming or AST transformations that make debugging difficult.Avoid Direct Jenkins API Calls
Warning
Do not invoke Jenkins internal APIs (e.g.,
hudson.model.*
) from yourJenkinsfile
.
For advanced integration, develop a custom Pipeline Step Plugin instead.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.Don’t Perform Raw Network or I/O Operations
Warning
Never fetch URLs or read/write files directly in your
Jenkinsfile
.
Wrap these operations insh
,bat
, or custom steps to ensure proper error handling and resource cleanup.
References
- Jenkins Pipeline Syntax
- Jenkins Plugin Development – Pipeline Steps
- xmllint Documentation
- jq User Guide
Watch Video
Watch video content
Practice Lab
Practice lab