Search code examples
jenkins-pipeline

How to implement either tagging or build in jenkins pipeline?


I add a choice parameter in jenkins job, as follows: enter image description here

I'm trying to do builds or tags through a pipeline script that.

pipeline {

    agent { label 'docker-slave2' }

    stages {

        stage('addtag') {
            when {
                expression { params.TAG_OR_BUILD == 'ADDTAG' }
            }
            steps {
                echo "$params.TAG_OR_BUILD"
                }
        }
        
        stage('build') {
            
        }
        
        stage('upload')
        
    }
}

The first STAGE of the pipeline above is for TAG, the second and third STAGE are the BUILD steps.

Now I want to execute only the first stage of the pipeline when I select ADDTAG in the choice parameter and only the second and third stage of the pipeline when I select BUILD in the choice parameter, how can I modify the above pipeline to achieve this?


Solution

  • You need to define parameters before starting the stages under agent, like

    pipeline {
        agent { label 'docker-slave2' }
        parameters {
            choice(name: 'TAG_OR_BUILD', choices: ['ADDTAG', 'BUILD'], description: 'Select TAG or BUILD')
        }
        stages {
            stage('ADDTAG') {
                when {
                    expression { params.TAG_OR_BUILD == 'ADDTAG' }
                }
                steps {
                    echo 'Perform steps for TAG'
                    // Add the steps for tagging here
                }
            }
        stage('BUILD') {
            when {
                expression { params.TAG_OR_BUILD == 'BUILD' }
            }
            steps {
                echo 'Perform BUILD'
                // Add the steps for building here
            }
        }
    }
    }

    Make Sure You define the same parameters as it is case sensitives.