首页 > 解决方案 > Jenkinsfile 不考虑分支条件

问题描述

以下是我的阶段Jenkinsfile

  stages {
    
    stage("build") {
        when {
            expression {
                BRANCH_NAME = 'alerta_dev_infra'
            }
        }
        steps {
            echo 'buidling the webhook'
        }
    }

    stage("test") {
        when {
            expression {
                env.BRANCH_NAME = 'alerta*'
            }
        }
          steps {
              echo 'testing the webhook'
        }
    }

    stage("deploy") {
        when {
            expression {
                env.BRANCH_NAME = 'alerta_dev_infra'
            }
        }
          steps {
              echo 'deploying the webhook'
        }
    }

  }

但是,当它执行时:

14:10:00  Push event to branch alerta_dev_infra
14:10:00  Started by user pkaramol@foo.bar
14:10:00  Rebuilds build #9

14:10:49  First time build. Skipping changelog.
14:10:49  [Pipeline] }
14:10:49  [Pipeline] // stage
14:10:49  [Pipeline] withEnv
14:10:49  [Pipeline] {
14:10:49  [Pipeline] container
14:10:49  [Pipeline] { (hide)
14:10:49  [Pipeline] stage
14:10:49  [Pipeline] { (build)
14:10:49  Stage "build" skipped due to when conditional
14:10:49  [Pipeline] }
14:10:50  [Pipeline] // stage
14:10:50  [Pipeline] stage
14:10:50  [Pipeline] { (test)
14:10:50  Stage "test" skipped due to when conditional
14:10:50  [Pipeline] }
14:10:50  [Pipeline] // stage
14:10:50  [Pipeline] stage
14:10:50  [Pipeline] { (deploy)
14:10:50  Stage "deploy" skipped due to when conditional
14:10:50  [Pipeline] }
14:10:50  [Pipeline] // stage
14:10:50  [Pipeline] }
14:10:50  [Pipeline] // container
14:10:50  [Pipeline] }
14:10:50  [Pipeline] // withEnv
14:10:50  [Pipeline] }
14:10:50  [Pipeline] // node
14:10:50  [Pipeline] }
14:10:50  [Pipeline] // podTemplate
14:10:50  [Pipeline] End of Pipeline

标签: jenkinsgroovyjenkins-pipeline

解决方案


我使用了 Choice Parameter 提供了三个选项供分支选择:master、develop 和 feature-1 在此处输入图像描述

这是以BRANCH_NAME参数为条件时使用的管道代码

pipeline {
    agent any
    
    stages {
        stage ('Build in master') {
            when {
                expression { params.BRANCH_NAME == 'master' }
            }
            
            steps {
                echo "Building in master"
            }
        }
        
        stage ('Build in develop')
        {
            when {
                expression { params.BRANCH_NAME == 'develop' }
            }
            
            steps {
                echo "Building in develop"
            }
        }
        
        stage ('Build in feature')
        {
            when {
                expression { params.BRANCH_NAME == 'feature-1' }
            }
            
            steps {
                echo "Building in feature-1"
            }
        }
    }
}

管道作业的输出: 在此处输入图像描述


推荐阅读