How to define and iterate over map in Jenkinsfile

前提是你 提交于 2020-01-12 05:26:07

问题


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.

I have these variables:

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

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}'"
}

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.


回答1:


There are some similar user-submitted examples in the Jenkins documentation.

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]
  }
}



回答2:


You can iterate over a map like this:

def map = [Io: 1, Europa: 2, Ganymed: 3]
for (element in map) {
    echo "${element.key} ${element.value}"
}

I don't know if a dynamic count of stages is useful. Maybe you could use parallel nodes, but I don't know if that's possible.




回答3:


Since May 30, 2017 you can iterate over Maps without workarounds.
You need to upgrade Pipeline: Groovy plugin to >= 2.33
Related issue: https://issues.jenkins-ci.org/browse/JENKINS-27421

Plugin changelog: https://plugins.jenkins.io/workflow-cps

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

for(element in mymap) {
    sh "make build KEY=${element.key} VALUE=${element.value}"
}



回答4:


There are have another simple way for parse json object to groovy object - Parsing and producing JSON

import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText('{ "myList": [4, 8, 15, 16, 23, 42] }')
println(object.myList)


来源:https://stackoverflow.com/questions/42770775/how-to-define-and-iterate-over-map-in-jenkinsfile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!