Jenkins声明性管道使用正则表达式101

时间:2017-12-06 16:19:55

标签: regex jenkins jenkins-pipeline jenkins-declarative-pipeline

我是声明性管道的新手并探索其功能。我试着用正则表达式。以下示例是反复试验的结果。那里有更好的解决方案吗?我正在寻找一种新的闪亮的声明性管道方式,如果有的话。

我没有得到的是,为什么我必须使用script{}-Enviroment,为什么我必须使用局部变量(def matcherX)?

工作示例,然后是第一个attemts:

工作示例:

pipeline {
    environment {
        dummyText = 'aaa123aaa'
        transfare = ''
    }
    agent any
    stages {
        stage('regex') {
            steps{
                script{
                    def matcherX = dummyText =~ /(\d+)/
                    transfare = matcherX[0][0]
                    echo transfare     // results in 123
                }
            } 
        }
    }
}

错误:没有脚本{}

/*
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 11: Expected a step @ line 11, column 21.
                       def matcherX = dummyText =~ /(\d+)/
                       ^
WorkflowScript: 12: Expected a step @ line 12, column 21.
                       transfare = matcherX[0][0]
*/

错误:使用脚本但使用全局变量

//script{
//                    transfare = dummyText =~ /(\d+)/
/*

// No line displayed where error occured???                    
an exception which occurred:
    in field org.jenkinsci.plugins.pipeline.modeldefinition.withscript.WithScriptScript.script
    in object org.jenkinsci.plugins.pipeline.modeldefinition.agent.impl.LabelScript@192ebed
    in field groovy.lang.Closure.delegate
    in object org.jenkinsci.plugins.workflow.cps.CpsClosure2@31fd6bc8
    in field groovy.lang.Closure.delegate
    in object org.jenkinsci.plugins.workflow.cps.CpsClosure2@609aa9b5
    in field org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.closures
    in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@3e51c1c3
    in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@3e51c1c3
Caused: java.io.NotSerializableException: java.util.regex.Matcher
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:860)
    at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
    at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
*/

1 个答案:

答案 0 :(得分:0)

脚本块表示偏离纯声明性语法。理想情况下,构建(就像任何其他进程一样)可以利用纯粹的声明性语法来避免步骤之间的隐式依赖。

匹配器类型的全局变量无法序列化,需要在Jenkins主服务器和从服务器之间传递它(我猜)。