如何在Jenkins声明式管道中循环参数化并行阶段? (或者脚本化的管道,如果声明式不能)
这是我简单的伪示例。如何循环(“部署serverN”)阶段?
数组可能具有1..n变量。
我不想重复代码。詹金斯管道中一定有办法吗?还是我应该使用矩阵。我已经尝试了一些,但是没有成功。
@Library('adm-jenkins-lib@trunk')
def SERVERS = ['server1.com','server2.com',...]
deployPipeline([servers: SERVERS, manage_tasks: TASKS])
...
def call(Map params) {
pipeline {
agent any
environment {
}
stages {
stage ('common task') {
}
stage ('Deploying..') {
parallel {
stage ('deploy server1') {
stages {
stage ('deploy tasks #1') {
steps { ... }
}
stage ('deploy tasks #2') {
steps { ... }
}
}
stage ('deploy server2') {
stages {
stage ('deploy tasks #1') {
steps { ... }
}
stage ('deploy tasks #2') {
steps { ... }
}
}
}
}
}
}
}
}
我也尝试过这种方法,但是由于前一阶段不依赖于下一阶段,所以它并不是完美的。
stage ('deploy serverX') {
when { expression { params.manage_tasks =~ /task01/ } }
steps {
script {
servers = params.servers
servers.each { server ->
deploys[server] = {
sh "run task#1 stuff.."
}
}
parallel deploys
}
}
}
它在Blue Ocean中应该看起来像这样(但是动态创建的): It should look like this in Blue Ocean
答案 0 :(得分:0)
我有解决方法:
至少将Blue Ocean更新到版本1.22,以正确查看管道。
按照@ zett42的建议安装库https://github.com/comquent/imperative-when。
此示例是脚本管道。 (我没有找到声明性管道的解决方案)
@Library('adm-jenkins-lib@trunk') _
properties([
parameters([
string(name: 'countTotal', defaultValue: '4'),
choice(name: 'servers', choices: ['all', '1', '2','3','4'], description: 'Run on specific platform'),
choice(name: 'manage_steps', choices: ['all_tasks','common_task','deploy_task','test_task'], description: 'Choose task')
])
])
node{
stage('common task'){
when(params.manage_steps ==~ /common_task|all_tasks/) {
sh "echo common task"
}
}
def stages = [failFast: true]
for (int i = 1; i < params.countTotal.toInteger()+1; i++) {
if (params.servers == 'all' || params.servers == i.toString() )
{
def vmNumber = i //alias the loop variable to refer it in the closure
stages["server${vmNumber}"] = {
stage("deploy ${vmNumber}") {
when(params.manage_steps ==~ /deploy_task|all_tasks/) {
sh "echo deploy; sleep 5"
}
}
stage("test ${vmNumber}") {
when(params.manage_steps ==~ /test_task|all_tasks/) {
sh "echo testing; sleep 5"
}
}
}
}
}
parallel stages
}