Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

jenkins - How to define and iterate over map in Jenkinsfile

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...