shell命令返回空字符串时执行阶段

时间:2018-07-31 16:25:00

标签: jenkins-pipeline

我试图创建仅在shell命令返回空字符串的情况下才执行一系列步骤的管道。 这是整个管道,相关部分位于“启动容器”阶段:

pipeline {
  agent {
    docker {
      image 'maven:3-alpine'
      args '-v m2:/root/.m2'
    }
  }
  stages {
    stage('Build') {
      steps {
        sh 'mvn verify -DskipTests'
        archiveArtifacts(artifacts: 'target/*.war', fingerprint: true, onlyIfSuccessful: true)
      }
    }
    stage('Test') {
      post {
        always {
          junit 'target/surefire-reports/**/*.xml'

        }
      }
      steps {
        sh 'mvn test'
      }
    }
    stage('Deploy [dev]') {
      environment {
        CONTAINER = 'containerName'
        STARTUP_LOG = 'INFO: Server startup'
      }
      stages {
        stage('Install docker') {
          steps  {
            sh 'apk update && apk add docker'
          }
        }
        stage('Start container') {
          when {
            expression {
              sh '''if [ -z $(docker ps -f name=$CONTAINER -q) ]; then true; else false; fi'''
            }
          }
          steps {
            sh '''docker start $CONTAINER'''
            sh '''(docker logs -f --tail 10 $CONTAINER 2>&1 &) | grep -q "$STARTUP_LOG"'''
          }
        }
        stage('Deploy WAR') {
          steps {
            echo 'deploy war file'
            echo 'smoke test'
          }
        }
      }
    }
    stage('Acceptance') {
      steps {
        echo 'deploy stubs'
        echo 'run cucumber tests'
        echo 'publish report'
      }
    }
    stage('Release') {
      when {
        expression {
          env.BRANCH_NAME == 'master'
        }

      }
      steps {
        echo 'releasing'
        echo 'time to deploy to UAT'
      }
    }
  }
}

问题是在执行when表达式时出现红色标记:

[test_master-YKUBYJHFWV5SAO5BKANKYXEX6RUGQUBB2GGZLHYPHNUKZELZPATQ] Running shell script

+ docker ps -f name=containerName -q
+ [ -z c504c975f632 ]
+ false
script returned exit code 1

我以为如果表达式返回false或null,那么关联的阶段将不会执行,但是显然,我的理解是错误的...

有关如何实现此目标的任何建议?可能无需重复进行一些魔术操作:-D

更新

我已经通过在returnStatus:true命令中添加参数sh来解决了构建错误,但是仍然不能阻止该步骤的执行。

我已经替换了“开始容器”阶段,现在看起来像这样:

    stage('Start container') {
      when {
        expression {
          sh script: '''if [ -z $(docker ps -f name=$CONTAINER -q) ]; then true; else false; fi''', returnStatus: true
        }
      }
      steps {
        sh '''docker start $CONTAINER'''
        sh '''(docker logs -f --tail 10 $CONTAINER 2>&1 &) | grep -q "$STARTUP_LOG"'''
      }
    }

1 个答案:

答案 0 :(得分:1)

expression块实际上等效于管道script块,因为它只能包含常规脚本,因此应将以上阶段更改为

    stage('Start container') {
      when {
        expression {
          def containerId = sh(script: 'docker ps -f name=$CONTAINER -q', returnStdout: true)
          return containerId.trim() == ""
        }
      }
      steps {
        sh "docker start $CONTAINER"
        sh '''(docker logs -f --tail 10 $CONTAINER 2>&1 &) | grep -q "$STARTUP_LOG"'''
      }
    }

仔细阅读文档通常会有所帮助...