Bash For Loop Not Working in Jenkins Pipeline

bashJenkins

Following is my code

     stage ('Connect to cluster (update kubeconfig)') {
        steps {
            script {
                dir("${env.WORKSPACE}/gke-infra-creation") {
                def jsonObj;
                jsonObj = readJSON file: 'parameters.json'

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

It is failing with below error

  org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
  WorkflowScript: 53: unexpected char: '\' @ line 53, column 29.
                   sh "for \i in ${jsonObj.ns}; do kubectl create namespace $i}; done"
                           ^

  1 error

  at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:309)

If I try with $i, then it fails with below error

 hudson.remoting.ProxyException: groovy.lang.MissingPropertyException: No such property: i for class: WorkflowScript

Any suggestions to resolve this issue.

Best Answer

  • The first i doesn't have any special characters, so doesn't need to be escaped at all.
  • The correct way to escape a literal $ is \$.
  • You have an extraneous bracket after $i.

Try:

sh "for i in ${jsonObj.ns}; do kubectl create namespace \$i; done"