Search code examples
jenkinsjenkins-pipeline

How to avoid building the docker image if stage is skipped?


My pipeline has a condition, wherein it runs the Node stage only if the branch is master. My problem is that the node:8 image is pulled by docker even if the stage is skipped. Is there a way to avoid this?

pipeline {
    agent any

    stages {
        stage('Node') {
            agent {
                docker { image 'node:8' }
            }
            when {
                branch 'master'
            }
            steps {
                sh 'node -v'
            }
        }
        stage('Maven') {
            agent {
                docker { image 'maven:3' }
            }
            steps {
                sh 'mvn -v'
            }

        }
    }
}

Solution

  • The when condition is evaluated on the agent. That's why the image is pulled. However, you can change this behaviour by using the beforeAgent option:

    when {
        beforeAgent true
        branch 'master'
    }
    

    This will cause the when statement to be evaluated before entering the agent and should avoid pulling the image.