Home > Back-end >  Not able to use for loop using bash in Jenkins pipeline
Not able to use for loop using bash in Jenkins pipeline

Time:05-25

Following is my code

      def jsonObj;
      jsonObj = readJSON file: 'vars.json'

                sh "gcloud container clusters get-credentials ${jsonObj.cluster_name} --zone ${jsonObj.zone} --project ${jsonObj.project}"
                sh "echo ${jsonObj.ns}"         
                sh "kubectl get nodes"
                sh "for i in ${jsonObj.ns}; do kubectl create namespace \$i; done"
              

The variable file 'vars.json' is as shown below

        "ns": ["dev","qa","sbx"]

But when I execute my pipeline , the values from the variable are extracted with the other characters because of which the subsequent operation is failing

       echo '[dev,' qa, 'sbx]'
     [dev, qa, sbx]
       for i in '[dev,' qa, 'sbx]'
       kubectl create namespace '[dev,'
     The Namespace "[dev," is invalid: .

Any suggestions to resolve this issue ?

CodePudding user response:

The problem here is that jsonObj is a Map type in Groovy with a List type at the ns key, and your expectation is that when you implicitly cast this to a string during interpolation, then it will become iterable in the shell interpreter as well. Groovy types and shell interpreter type constructors are not syntactically isomorphic. You would want to use a Groovy iterator for the Groovy variable instead:

Map jsonObj = readJSON file: 'vars.json'
jsonObj.ns.each() { namespace ->
  sh(label: 'Create Kubernetes Namespace', script: "kubectl create namespace ${namespace}")
}

and then the shell interpreter command will receive the already resolved namespace variable from the pipeline correctly.

  • Related