如何在Jenkinsfile中定义和迭代地图 [英] How to define and iterate over map in Jenkinsfile

查看:231
本文介绍了如何在Jenkinsfile中定义和迭代地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对groovy的了解远不止于我对Jenkinsfiles的了解.我试图弄清楚是否有可能在Jenkinsfile中定义一个映射,然后可以以"for循环"方式应用该映射.

My knowledge of groovy doesn't go very far beyond what little I know about Jenkinsfiles. I'm trying to figure out if it's possible to have a map defined in a Jenkinsfile that can then be applied in a "for loop" fashion.

我有这些变量:

mymap = {
    "k1": "v1"
    "k2": "v2"
    "k3": "v3" 
}

我的Jenkins文件中有一个stage,如下所示:

I have a stage in my Jenkinsfile that looks like this:

stage('Build Image') {
    withCredentials([[<the credentials>]) {
    sh "make build KEY={k1,k2,k3} VALUE='{v1,v2,v3}'"
}

是否可以为mymap中的每个配对建立一个Build Image阶段?我的尝试还没有运气.

Is there a way to make a Build Image stage for each of the pairings in mymap? I haven't had any luck with what I've tried.

推荐答案

也有一些类似的类似的事情应该起作用:

Something like this should work:

def data = [
  "k1": "v1",
  "k2": "v2",
  "k3": "v3",
]

// Create a compile job for each item in `data`
work = [:]
for (kv in mapToList(data)) {
  work[kv[0]] = createCompileJob(kv[0], kv[1])
}

// Execute each compile job in parallel
parallel work


def createCompileJob(k, v) {
  return {
    stage("Build image ${k}") { 
      // Allocate a node and workspace
      node {
        // withCredentials, etc.
        echo "sh make build KEY=${k} VALUE='${v}'"
      }
    }
  }
}

// Required due to JENKINS-27421
@NonCPS
List<List<?>> mapToList(Map map) {
  return map.collect { it ->
    [it.key, it.value]
  }
}

这篇关于如何在Jenkinsfile中定义和迭代地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆