lundi 3 août 2020

Jenkinsfile setting stageResult variable based on conditions

I'm trying to script a Jenkinsfile in Declarative Syntax, requirement here is if set environment variables are not a match then pipeline stage should be depict as "Aborted" but the build status could be either Aborted or unstable, on Jenkins online documentation and from Snippet Generator did see the following style

catchError(buildResult: 'ABORTED', stageResult: 'ABORTED') {
    // some block
}

catchError does not serve my purpose as it is appropriate for use when the script inside the stage does not return true or if there is an execution error, although default when condition in Jenkins Declarative Syntax is appropriate, Jenkins does not allow setting stage result to 'ABORTED'

when {
                expression {
                    SCM_BRANCH_NAME ==~ /(master|QA)/
                }
                expression{
                    ENVIRONMENT ==~ /(QA)/
                }
                allOf{
                    environment ignoreCase: true,name: 'PRODUCT_NAME' , value: 'PRODUCT-1'
                }
            }

Please view the Sample Jenkinsfile below using if and else format Sample Jenkinsfile

pipeline {
    agent {
        node {
            label 'master'
        }
    }
    environment{
        ENVIRONMENT = "QA"
        PRODUCT_NAME = "PRODUCT-1"
        SCM_BRANCH_NAME = "master"
    }
    stages{
        stage('Testing-1') {
            when{
            expression{
                    ENVIRONMENT ==~ /(QA)/
                }
            }
            steps {
                script {
                    if (PRODUCT_NAME == PRODUCT-1){
                        sh """
                        echo "Reached Here ${ENVIRONMENT} - ${PRODUCT_NAME} - ${SCM_BRANCH_NAME}"
                        // do testing for product 1
                        """  
                        
                    }
                    else{
                        stageResult = 'ABORTED'
                        echo "PRODUCT not Available for Testing"
                    }
                }
            }
        }

        stage('Testing-2'){
            steps{
                sh '''
                    echo "Reached Second Stage"
                '''
            }
        }
    }
}    

Any suggestions of how to implement the scenario that if conditions are not met set the stageResult as Abort, any suggestions either with a plugin or with a sample notation script is greatly appreciated

Thanks

Aucun commentaire:

Enregistrer un commentaire