How to define and iterate over map in Jenkinsfile

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

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.