Search code examples
jenkinsgroovyjenkins-pipelinejenkins-groovy

Can I create dynamically stages in Jenkins pipeline, which will run in the sequence?


I have a function which create dynamically stages from the map variable and they run in the parallel. Everything is good. But I want to run this function also when I need to create dynamically stages from the map variable but in order.

Map item_1 = [
  'Data_1' : 'sdfdfd',
  'Data_2' : 'dfdfdfd'
  ]

// Function for generate GitCheckout stages
def gitcheckoutStages(item, gitCredentials, mode) {
  def map_steps = [:]
  item.each { key, value ->
    println "$key: $value"
    map_steps["$key"] = {
      stage ("Checkout on the tag in the repo $key") {
        dir("$key") {
          utils.checkoutSCM("$value", env.GIT_ANDROID_BRANCH, "$gitCredentials")
          env."$key" = sh(script: "git tag --list --sort=-taggerdate ${params.VERSION} | head -n 1", returnStdout: true).trim()
          sh "git tag"
          sh "echo ${env."$key"}"
        }
        if (env."$key" == "") {
          error("Can't find the tag with selected pattern")
        }
        if (params.VERSION ==~ /.*SNAP/) {
          env.DEBUG_PARAMETER = "Debug"
        } else {
          env.DEBUG_PARAMETER = "Release"
        }
        dir("$key") {
          sh "git checkout ${env."$key"}"
          sh "git log -1"
        }
      }
    }
  }
  if ("$mode" == "true") {
    parallel(map_steps)
  } else {
    return(map_steps);
  }
}

pipeline {
  agent {
      label 'android-executor'
  }
  options {
      disableConcurrentBuilds()
      timestamps()
      ansiColor('xterm')
  }
  post {
    always {
      script {
        utils.cleanUpWorkspace(env.WORKSPACE)
      }
    }
  }
  stages {
    stage ("Git checkout for all repos") {
      steps {
        script {
          gitcheckoutStages(item_1, gitCredentials, "false")
        }
      }
    }
 }
}

I try everything that I can, but it falls. I want that I can use function for creation dynamically stages in parallel or in order(one by one) through pass argument to function.


Solution

  • I can't edit the other answer but basically each, just like that doesn't work for a map, you should do this instead (considering the map of your stages being map_steps):

    map_steps.each{ key,val ->
     val()
    }
    

    For a little background check, what you are storing are Closures, so to launch them you need to call them as a function.

    The last remark of Iterokun is really important.