我如何在 jenkinsfile 中添加条件步骤

How i can add conditional steps in jenkinsfile

我试图在 Jenkinsfile 中执行多个步骤,这些步骤包含 shell 命令,这需要一些时间才能得到最终输出。

由于这些步骤相互依赖,如果第一个 cmd 的输出等于某个值("session started"),我如何添加条件,然后执行第二个,如果不是,则打印一些消息 =("string").

阶段(){ 代理人{

    docker {
            label 'MyDocker',
            image 'myIMG'
            }
        }
        steps {
            sh label: 'Creating container', script: 'docker run --privileged -d -p 4750:4723 --name mycontainer myimg'
            sh label: 'Building ', script: 'docker exec -it mycontainer test'
        }
    }

如果您在步骤级别需要这样的条件,则必须使用 script 步骤并编写一些 Groovy 代码。

stage() { 
    agent {
        docker {
            label 'MyDocker',
            image 'myIMG'
        }
    }
    steps {
        script {
            def output = sh returnStdout: true, label: 'Creating container', script: 'docker run --privileged -d -p 4750:4723 --name mycontainer myimg'
            if( output.indexOf('session started') >= 0 ) {
                sh label: 'Building ', script: 'docker exec -it mycontainer test'
            }
            else {
                echo "This is the output: $output"
            }
        }
    }
}

我已将参数 returnStdout: true 添加到 return 来自 shell 命令的输出。

为了检查输出,我使用子字符串搜索 output.indexOf 来使代码更健壮。您当然可以通过将 1:1 替换为 output == 'session started' 来比较它。