如何消除Jenkins声明式流水线中的重复阶段?
不用保留重复阶段,这几种方法可以帮你大幅精简代码
方案1:用Groovy函数封装重复逻辑
你之前的理解有误——函数里完全可以调用Jenkins流水线步骤(比如bat),只要把逻辑封装成函数,后续每个阶段只需要传参数调用即可:
pipeline { agent any stages { stage('First Stage') { steps { script { runApp('FirstFile') } } } stage('Nth Stage') { steps { script { runApp('NthFile') } } } // 新增阶段直接加一行调用就行 } } // 封装所有重复逻辑的函数 def runApp(String fileName) { def programToRun = "\"${env.APPLICATION_PATH}\" /path:Output /file:${fileName}" def errorLevel = bat( returnStatus: true, script: programToRun ) if (errorLevel == 0) { DoSomething() // 这里直接用你已有的自定义方法 } }
方案2:循环批量生成阶段
如果有10+个阶段,更高效的方式是把所有参数存到列表里,用循环自动生成所有阶段,连stage的定义都不用重复写:
pipeline { agent any stages { script { // 维护这个列表就行,新增文件直接加在这里 def fileList = ['FirstFile', 'SecondFile', 'ThirdFile', 'NthFile'] fileList.each { fileName -> stage("Process ${fileName}") { steps { script { def programToRun = "\"${env.APPLICATION_PATH}\" /path:Output /file:${fileName}" def errorLevel = bat( returnStatus: true, script: programToRun ) if (errorLevel == 0) { DoSomething() } } } } } } } }
方案3:Matrix阶段(适合多参数组合场景)
如果除了文件名,还有其他参数需要组合(比如不同的输出路径),可以用声明式的matrix阶段自动生成所有参数组合的阶段:
pipeline { agent any stages { stage('Batch Process') { matrix { axes { axis { name 'TARGET_FILE' values 'FirstFile', 'NthFile', ... } // 如果需要多参数组合,再加一个axis即可 // axis { // name 'OUTPUT_PATH' // values 'Output', 'Backup' // } } stages { stage("Run for ${TARGET_FILE}") { steps { script { def programToRun = "\"${env.APPLICATION_PATH}\" /path:Output /file:${TARGET_FILE}" def errorLevel = bat( returnStatus: true, script: programToRun ) if (errorLevel == 0) { DoSomething() } } } } } } } } }
内容的提问来源于stack exchange,提问作者Tim
相关产品推荐
相关产品推荐

