Not able to read the item from list using for loop in the jenkins pipeline stage

5/18/2020

Running one linux command and saving the ouput of the command as list and then reding the list item one by one.

stage('NAMESPACE Availability') {
            node ('master'){
                  withEnv(["KUBECONFIG=${JENKINS_HOME}/.kube/config"]){
                  NS_list = sh (
                  script: '''kubectl get ns | awk '{print \$1}' | awk '{\$1=\$1; print "[\\x27" $0 "\\x27]"}' FS='\n' OFS="','" RS='' ''',
                  returnStdout: true
                  ).trim()
                  echo "${NS_list}"
                  NS(NS_list)
             }

      }
}
  def NS(list) {
     for (i in list) {
        echo "${i}"
        if ( i == "${NAME_SPACE}" ) {
            sh "kubectl delete all --all -n '${NAME_SPACE}' && kubectl delete '${NAME_SPACE}' "
        break;
    }
  }
}

Rather then reading as Item its reading as character , Lets say if command output is ['NAME','b2','b6','b7','cert-manager','default'] its reading as below output.

[Pipeline] echo
[
[Pipeline] echo
'
[Pipeline] echo
N
[Pipeline] echo
A
[Pipeline] echo
M
[Pipeline] echo
E
[Pipeline] echo

[Pipeline] echo
'
[Pipeline] echo
,
[Pipeline] echo
'
-- me25
groovy
jenkins
jenkins-pipeline
kubernetes

2 Answers

5/18/2020

You haven't declared NS_list, that will store everything as a string. Add def NS_list = [] at the beginning of your pipeline

-- hdhruna
Source: StackOverflow

5/18/2020

I solved my problem as per below changes. Rather then using for(loop).. i used ".contains"

stage('NAMESPACE Availability') {
            node ('master'){
                  withEnv(["KUBECONFIG=${JENKINS_HOME}/.kube/config"]){
                  NS_list = sh (
                  script: '''kubectl get ns | awk '{print \$1}' ''',
                  returnStdout: true
                  ).trim()
                  def lst = "${NS_list}";
                      NS = (lst.contains( "${NAME_SPACE}" ));
                      echo "${NS}"
                      if ( NS == true ) {
                         sh "kubectl delete all --all -n ${NAME_SPACE} "
                      }
                      else {
                         sh "kubectl create ns ${NAME_SPACE}"
                      }

        }
-- me25
Source: StackOverflow