jenkinsjenkins-pipelinejenkins-job-dsl

Jenkins DSL Pipeline: delete a job from its pipeline


I have a Jenkins pipeline job that (among other things) creates another pipelineJob (to cleanup everything afterwards) using Job DSL plugin.

pipeline {

    agent { label 'Deployment' }

    stages {
        stage('Clean working directory and Checkout') {
            steps {
                deleteDir()
                checkout scm
            }
        }

        // Complex logic omitted

        stage('Generate cleanup job') {
            steps {
                build job: 'cleanup-job-template',
                        parameters: [
                                string(name: 'REGION', value: "${REGION}"),
                                string(name: 'DEPLOYMENT_TYPE', value: "${DEPLOYMENT_TYPE}")
                        ]
            }
        }
    }
}

The thing is that I need this newly generated job to be built only once and then, if the build was successful, the job should be deleted.

pipeline {
   stages {
        stage('Cleanup afterwards') {
            // cleanup logic
        }
   }
    post { 
        success { 
            // delete this job?
        }
    }

}

I thought, that this can be done using Pipeline Post Action, but, unfortunately, I couldn't find any out-of-the-box solution for this. Is it possible to achieve this at all?


Solution

  • You can achieve this using the post Groovy and then you will need to write some groovy code in order to delete the job:

    #!/usr/bin/env groovy
    import hudson.model.*
    pipeline {
       agent none
       stages {
            stage('Cleanup afterwards') {
                // cleanup logic
                steps {
                    node('worker') {
                        sh 'ls -la'
                    }
                }
            }
       }
       post { 
           success { 
               script {
                   jobsToDelete = ["<JOB_TO_DELETE"]
                   deleteJob(Hudson.instance.items, jobsToDelete)
               }
           }
       }
    }
    
    def deleteJob(items, jobsToDelete) {
        items.each { item ->
          if (item.class.canonicalName != 'com.cloudbees.hudson.plugins.folder.Folder') {
            if (jobsToDelete.contains(item.fullName)) {
              manager.listener.logger.println(item.fullName)
              item.delete()
            }
          }
        }
    }
    

    Tested both cases and work on Jenkins 2.89.4