11

PROBLEM

Given that all the jobs have string LEVEL_X in it's job name, where X is a number > 1. I want every job with X = n to surveil every job with X = n-1, and start building if each of them is finished with success. And I want the job with X = n to surveil the other jobs with an interval of 1 minute.

First of all, I am interested in knowing what the best way is to do that, second I want the solution if one can be implemented by a small script, maybe a groovy script which can be run in system groovy script using the GROOVY PLUGIN.

Akhil Jain
  • 13,872
  • 15
  • 57
  • 93
Gogi
  • 1,695
  • 4
  • 23
  • 36

1 Answers1

45

Here are some hints and code snippets:

  • There is a Groovy Script console at http://<jenkins-server>/script that will help you with debugging your scripts.
  • Here is a link to Jenkins Java API.
  • Code snippet that outputs all job names:

    def hi = hudson.model.Hudson.instance
       hi.getItems(hudson.model.Project).each {project ->
       println(project.displayName)
    }
    
  • Code snippet that extracts n from LEVEL_n (implemented as closure):

    def level = { name ->
      def ret = 0
      name.eachMatch(~'LEVEL_([1-9]+[0-9*])', {ret = it[1].toInteger()})
      return ret
    }
    
  • Code snippet that gets statuses for all the latest builds:

    def hi = hudson.model.Hudson.instance
    hi.getItems(hudson.model.Project).each {project ->
      println(project.lastBuild.result)
    }
    
  • Link to the method that starts a build.

Note: things get a bit hairier if you are using Matrix builds. But as long as you don't this should be enough.

malenkiy_scot
  • 16,415
  • 6
  • 64
  • 87
  • 2
    +1 for the jenkins server script url - the node groovy console is worthless, since it doesn't import all the classes. – Epu Mar 29 '13 at 22:39
  • In the groovy console I'm finding the full script/command has to be all on one line, otherwise various syntax errors. e.g. the job name snippet works for me like this: '''def hi = hudson.model.Hudson.instance; hi.getItems(hudson.model.Project).each {project -> println(project.displayName) }''' – gaoithe Aug 30 '16 at 10:20
  • 1
    just a FYI for folks; some of these API methods have to be given scriptApproval to run in a job. – jxramos Dec 04 '18 at 19:49