Jenkins pipeline if else not working

后端 未结 3 415

I am creating a sample jenkins pipeline, here is the code.

pipeline {
    agent any 

    stages {    
        stage(\'test\') { 
            steps { 
                   


        
相关标签:
3条回答
  • 2021-01-30 05:37

    It requires a bit of rearranging, but when does a good job to replace conditionals above. Here's the example from above written using the declarative syntax. Note that test3 stage is now two different stages. One that runs on the master branch and one that runs on anything else.

    stage ('Test 3: Master') {
        when { branch 'master' }
        steps { 
            echo 'I only execute on the master branch.' 
        }
    }
    
    stage ('Test 3: Dev') {
        when { not { branch 'master' } }
        steps {
            echo 'I execute on non-master branches.'
        }
    }
    
    0 讨论(0)
  • 2021-01-30 05:41

    your first try is using declarative pipelines, and the second working one is using scripted pipelines. you need to enclose steps in a steps declaration, and you can't use if as a top-level step in declarative, so you need to wrap it in a script step. here's a working declarative version:

    pipeline {
        agent any
    
        stages {
            stage('test') {
                steps {
                    sh 'echo hello'
                }
            }
            stage('test1') {
                steps {
                    sh 'echo $TEST'
                }
            }
            stage('test3') {
                steps {
                    script {
                        if (env.BRANCH_NAME == 'master') {
                            echo 'I only execute on the master branch'
                        } else {
                            echo 'I execute elsewhere'
                        }
                    }
                }
            }
        }
    }
    

    you can simplify this and potentially avoid the if statement (as long as you don't need the else) by using "when". See "when directive" at https://jenkins.io/doc/book/pipeline/syntax/. you can also validate jenkinsfiles using the jenkins rest api. it's super sweet. have fun with declarative pipelines in jenkins!

    0 讨论(0)
  • 2021-01-30 05:52
            if ( params.build_deploy == '1' ) {
                println "build_deploy 是 ${params.build_deploy}"
                  jobB = build job: 'k8s-core-user_deploy', propagate: false, wait: true, parameters: [
                             string(name:'environment', value: "${params.environment}"),
                             string(name:'branch_name', value: "${params.branch_name}"),
                             string(name:'service_name', value: "${params.service_name}"),                      
                         ]
                println jobB.getResult()
            }
    
    0 讨论(0)
提交回复
热议问题