1
votes

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?

2
Why do you need this to be an extra job? Why can‘t you do the cleanup in the same job? - Hendrik M Halkow
@HendrikMHalkow, that job creates some AWS cloudformation stack that is then tested. So, once tests are done this stack shall be removed. Cleanup job is here for this. - Enigo

2 Answers

3
votes

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

0
votes

You should do that all in one job instead of creating and deleting jobs. Use multiple stages for that, e.g. deploy test system, run tests / wait for tests to be finished, undeploy. No need for extra jobs. Example posted here: Can a Jenkins pipeline have an optional input step?