发布条件时的声明性管道

psy*_*tiq 18 jenkins

至于声明中的管道去詹金斯,我遇到麻烦时,关键字.

我一直在收到错误No such DSL method 'when' found among steps.我对Jenkins 2声明性管道有点新意,并不认为我将脚本管道与声明性管道混合在一起.

此管道的目标是mvn deploy在成功运行Sonar之后运行并发送失败或成功的邮件通知.我只希望在master或release分支上部署工件.

我遇到困难的部分是在帖子部分.该通知阶段是伟大的工作.请注意,我在没有when子句的情况下使用它,但确实需要它或等效的.

pipeline {
  agent any
  tools {
    maven 'M3'
    jdk 'JDK8'
  }
  stages {
    stage('Notifications') {
      steps {
        sh 'mkdir tmpPom'
        sh 'mv pom.xml tmpPom/pom.xml'
        checkout([$class: 'GitSCM', branches: [[name: 'origin/master']], doGenerateSubmoduleConfigurations: false, submoduleCfg: [], userRemoteConfigs: [[url: 'https://repository.git']]])
        sh 'mvn clean test'
        sh 'rm pom.xml'
        sh 'mv tmpPom/pom.xml ../pom.xml'
      }
    }
  }
  post {
    success {
      script {
        currentBuild.result = 'SUCCESS'
      }
      when { 
        branch 'master|release/*' 
      }
      steps {
        sh 'mvn deploy'
      }     
      sendNotification(recipients,
        null,             
        'https://link.to.sonar',
        currentBuild.result,
      )
    }
    failure {
      script {
        currentBuild.result = 'FAILURE'
      }    
      sendNotification(recipients,
        null,             
        'https://link.to.sonar',
        currentBuild.result
      )
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

cod*_*ass 22

在声明性管道的文档中,提到您不能whenpost块中使用.when只允许在stage指令中使用.所以你能做的是:

post {
success {
  script {
    if (${env.BRANCH_NAME} == 'master')
        currentBuild.result = 'SUCCESS'
  }
 }
// failure block
}
Run Code Online (Sandbox Code Playgroud)

  • 可能需要使用“ $ {env.BRANCH_NAME}”而不是“ $ {GIT_LOCAL_BRANCH}”。 (2认同)
  • 对我来说,这仅在编写不带“${}”的变量时有效。这是詹金斯行为最近的变化吗? (2认同)

Nag*_*gev 9

使用GitHub Repository和Pipeline插件,我有一些类似的东西:

pipeline {
  agent any
  stages {
    stage('Build') {
      steps {
        sh '''
          make
        '''
      }
    }
  }
  post {
    always {
      sh '''
        make clean
      '''
    }
    success {
      script {
        if (env.BRANCH_NAME == 'master') {
          emailext (
            to: 'engineers@green-planet.com',
            subject: "${env.JOB_NAME} #${env.BUILD_NUMBER} master is fine",
            body: "The master build is happy.\n\nConsole: ${env.BUILD_URL}.\n\n",
            attachLog: true,
          )
        } else if (env.BRANCH_NAME.startsWith('PR')) {
          // also send email to tell people their PR status
        } else {
          // this is some other branch
        } 
      }
    }     
  }
}
Run Code Online (Sandbox Code Playgroud)

这样,可以根据所构建分支的类型发送通知。有关详细信息,请参见管道模型定义以及服务器上的可用全局变量参考,网址http:// your-jenkins-ip:8080 / pipeline-syntax / globals#env