Split jenkins variable and trigger multiple jobs

6/6/2018

I need to clean up some Kubernete namespaces(hello_namespace, second,my_namespace1, my_namespace45,my_namespace44 for example and I do it with a jenkins job. I read with kubectl the namespace I need to clean up and then I want to fire a job to delete it, My code should be something like that

    pipeline {
    agent { label 'master' }
    stages {

        stage('Clean e2e') {

            steps {
                script {
                 sh  "kubectl get namespace |egrep 'my_namespace[0-9]+'|cut -f1 -d ' '>result.txt"
                 def output=readFile('result.txt').trim()
                }
            }
    }

The ouput of this code will be the variable $output with the values: my_namespace1 my_namespace45 my_namespace44 Separated by line, now I want to fire a job with the namespace like parameter , how can I do that? (My problem is to read the file and fire independent job for each namespace) while (output.nextLine() callJob) The job call should be like

build job: 'Delete temp Stage', parameters:
                    [string(name: 'Stage', value: "${env.stage_name}")]
-- Guel135
jenkins
jenkins-pipeline
kubernetes

1 Answer

6/6/2018

I already got it :)

    #!groovy
pipeline {
    agent { label 'master' }

    stages {
        stage('Clean up stages') {

            steps {
                script {
                    sh '(kubectl get namespace |egrep "namespace[0-9]+"|cut -f1 -d " "|while read i;do echo -n $i";" ; done;)>result.txt'
                    def stages = readFile('result.txt').trim().split(';')
                    for (stage in stages) {
                        if (stage?.trim()) {
                             echo "deleting stage: $stage"
                            build job: 'Delete temp Stage', parameters:
                                    [string(name: 'Stage', value: "$stage")]
                            }
                       }
                }
            }
        }
    }
}
-- Guel135
Source: StackOverflow