Services DevOps DevSecOps Cloud Consulting Infrastructure Automation Managed Services AIOps MLOps DataOps Microservices 🔐 Private AINEW Solutions DevOps Transformation CI/CD Automation Platform Engineering Security Automation Zero Trust Security Compliance Automation Cloud Migration Kubernetes Migration Cloud Cost Optimisation AI-Powered Operations Data Platform Modernisation SRE & Observability Legacy Modernisation Managed IT Services 🔐 Private AI DeploymentNEW Products ✨ ZippyOPS AINEW 🛡️ ArmorPlane 🔒 DevSecOpsAsService 🖥️ LabAsService 🤝 Collab 🧪 SandboxAsService 🎬 DemoAsService Bootcamp 🔄 DevOps Bootcamp ☁️ Cloud Engineering 🔒 DevSecOps 🛡️ Cloud Security ⚙️ Infrastructure Automation 📡 SRE & Observability 🤖 AIOps & MLOps 🧠 AI Engineering 🎓 ZOLS — Free Learning Company About Us Projects Careers Get in Touch

Streamline Jenkins Pipelines with Conditional Stages

Streamline Jenkins Pipelines with Conditional Stages

Jenkins is a powerful automation tool used for continuous integration and continuous delivery (CI/CD). When building efficient Jenkins pipelines, it’s important to implement conditions that control which stages are executed. This can be achieved through the use of optional stages and conditional logic. In this guide, we’ll explore different methods for streamlining Jenkins pipelines with conditional stages, ensuring that each build process is executed only when necessary.

Diagram showing Jenkins pipelines stages with conditional logic and parallel execution

1. Conditional Stages Using Groovy’s Script Syntax

When defining conditional logic in a Jenkins pipeline, using Groovy’s conditionals in a script step offers flexibility. For instance, if you only want a stage to run when a specific condition is met, such as a boolean parameter like RELEASE, you can use a simple if statement.

Here’s an example of using conditionals in a script step:

pipeline {
    agent any
    parameters {
        booleanParam(name: "RELEASE", defaultValue: false)
    }
    stages {
        stage("Build") {
            steps {
                sh "./gradlew build"
            }
        }
        stage("Publish") {
            steps {
                script {
                    if (params.RELEASE) {
                        sh "./gradlew release"
                    }
                }
            }
        }
    }
}

While this works, the stage will still appear as executed even if no action was performed, which can be confusing during the build review process.

2. Streamlining with the when Directive

To make the pipeline more declarative and easier to follow, you can use the when directive. This allows Jenkins to conditionally skip or execute a stage based on specific conditions, such as a parameter being true or false.

Here’s how you can modify the pipeline using when:

pipeline {
    agent any
    parameters {
        booleanParam(name: "RELEASE", defaultValue: false)
    }
    stages {
        stage("Build") {
            steps {
                sh "./gradlew build"
            }
        }
        stage("Publish") {
            when {
                expression { params.RELEASE }
            }
            steps {
                sh "./gradlew release"
            }
        }
    }
}

This approach is not only more readable but also gives a clearer understanding of which stages were executed and which were skipped based on the conditions provided.

3. Handling Conditional Logic with if/else

For more complex scenarios where either one of two tasks should be executed (e.g., pre-release or full release), you can use an if/else block. This can be done either through a script or a declarative syntax.

pipeline {
    agent any
    parameters {
        booleanParam(name: "RELEASE", defaultValue: false)
    }
    stages {
        stage("Build") {
            steps {
                sh "./gradlew build"
            }
        }
        stage("Publish") {
            steps {
                script {
                    if (params.RELEASE) {
                        sh "./gradlew release"
                    } else {
                        sh "./gradlew preRelease"
                    }
                }
            }
        }
    }
}

While this solution works, the challenge is that Jenkins doesn’t show a clear distinction between pre-release and release stages in the build logs. To address this, we can improve the clarity by splitting them into separate stages.

4. Using Separate Stages for Pre-release and Release

Splitting stages into individual steps with the when directive allows Jenkins to clearly show which stage was executed.

pipeline {
    agent any
    parameters {
        booleanParam(name: "RELEASE", defaultValue: false)
    }
    stages {
        stage("Build") {
            steps {
                sh "./gradlew build"
            }
        }
        stage("Publish Pre-Release") {
            when { expression { !params.RELEASE } }
            steps {
                sh "./gradlew preRelease"
            }
        }
        stage("Publish Release") {
            when { expression { params.RELEASE } }
            steps {
                sh "./gradlew release"
            }
        }
    }
}

This structure enhances the pipeline’s clarity by making it easier to track which build path was followed (pre-release vs. release).

5. Enhancing Clarity with Parallel Execution in Jenkins Pipelines

To further optimize the pipeline, you can use parallel execution for conditions like pre-release and release stages. This not only shortens the overall pipeline execution time but also provides a better overview of the build process.

pipeline {
    agent any
    parameters {
        booleanParam(name: "RELEASE", defaultValue: false)
    }
    stages {
        stage("Build") {
            steps {
                sh "./gradlew build"
            }
        }
        stage("Publish") {
            parallel {
                stage("Release") {
                    when { expression { params.RELEASE } }
                    steps {
                        sh "./gradlew release"
                    }
                }
                stage('Pre-Release') {
                    when { expression { !params.RELEASE } }
                    steps {
                        sh "./gradlew preRelease"
                    }
                }
            }
        }
    }
}

By using parallel execution, Jenkins runs both the pre-release and release stages simultaneously, making the build process more efficient while keeping the pipeline graph easy to understand.

6. Handling Multiple Deployment Targets

In some cases, you may need to deploy to different environments (e.g., development, staging, production). This can be done using the switch statement, but to maintain a clean pipeline graph, we can split the deployment into separate stages.

Here’s an example of how to achieve this:

pipeline {
    agent any
    parameters {
        booleanParam(name: "RELEASE", defaultValue: false)
        choice(name: "DEPLOY_TO", choices: ["", "INT", "PRE", "PROD"])
    }
    stages {
        stage("Build") {
            steps {
                sh "./gradlew build"
            }
        }
        stage("Publish") {
            parallel {
                stage('Pre-Release') {
                    when { expression { !params.RELEASE } }
                    steps {
                        sh "./gradlew preRelease"
                    }
                }
                stage("Release") {
                    when { expression { params.RELEASE } }
                    steps {
                        sh "./gradlew release"
                    }
                }
            }
        }
        stage("Deploy") {
            parallel {
                stage("INT") {
                    when { expression { params.DEPLOY_TO == "INT" } }
                    steps {
                        sh "./deploy int"
                    }
                }
                stage("PRE") {
                    when { expression { params.DEPLOY_TO == "PRE" } }
                    steps {
                        sh "./deploy.sh pre"
                    }
                }
                stage("PROD") {
                    when { expression { params.DEPLOY_TO == "PROD" } }
                    steps {
                        sh "./deploy.sh prod"
                    }
                }
            }
        }
    }
}

In this pipeline, the Deploy stage is split into multiple parallel stages, making it clearer which environment the deployment is targeting.

Conclusion on Jenkins Pipelines with Conditional Stages

Using conditional logic in Jenkins pipelines can help you create more efficient and maintainable CI/CD workflows. By leveraging declarative syntax, the when directive, and parallel stages, you can ensure that each stage is executed only when necessary, providing a clear and concise pipeline graph. If you need help implementing these strategies or improving your DevOps practices, ZippyOPS offers comprehensive consulting, implementation, and managed services in areas like DevOps, DevSecOps, AIOps, MLOps, and more. For more information, visit our services page.

For businesses looking to optimize their infrastructure, ZippyOPS specializes in solutions for microservices, cloud automation, and security. Explore our solutions or learn about our products.

For personalized guidance, contact us at sales@zippyops.com.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top