how to get the trigger information in Jenkins programmatically how to get the trigger information in Jenkins programmatically jenkins jenkins

how to get the trigger information in Jenkins programmatically


I realise you probably no longer need help with this, but I just had to solve the same problem, so here is a script you can use in the Jenkins console to output all trigger configurations:

#!groovyJenkins.instance.getAllItems().each { it ->  if (!(it instanceof jenkins.triggers.SCMTriggerItem)) {    return  }  def itTrigger = (jenkins.triggers.SCMTriggerItem)it  def triggers = itTrigger.getSCMTrigger()  println("Job ${it.name}:")  triggers.each { t->    println("\t${t.getSpec()}")    println("\t${t.isIgnorePostCommitHooks()}")  }}

This will output all your jobs that use SCM configuration, along with their specification (cron-like expression regarding when to run) and whether post-commit hooks are set to be ignored.

You can modify this script to get the data as JSON like this:

#!groovyimport groovy.json.*def result = [:]Jenkins.instance.getAllItems().each { it ->  if (!(it instanceof jenkins.triggers.SCMTriggerItem)) {    return  }  def itTrigger = (jenkins.triggers.SCMTriggerItem)it  def triggers = itTrigger.getSCMTrigger()  triggers.each { t->    def builder = new JsonBuilder()    result[it.name] = builder {      spec "${t.getSpec()}"      ignorePostCommitHooks "${t.isIgnorePostCommitHooks()}"    }  }}return new JsonBuilder(result).toPrettyString()

And then you can use the Jenkins Script Console web API to get this from an HTTP client.

For example, in curl, you can do this by saving your script as a text file and then running:

curl --data-urlencode "script=$(<./script.groovy)" <YOUR SERVER>/scriptText

If Jenkins is using basic authentication, you can supply that with the -u <USERNAME>:<PASSWORD> argument.

Ultimately, the request will result in something like this:

{    "Build Project 1": {        "spec": "H/30 * * * *",        "ignorePostCommitHooks": "false"    },    "Test Something": {        "spec": "@hourly",        "ignorePostCommitHooks": "false"    },    "Deploy ABC": {        "spec": "H/20 * * * *",        "ignorePostCommitHooks": "false"    }}

You should be able to tailor these examples to fit your specific use case. It seems you won't need to access this remotely but just from a job, but I also included the remoting part as it might come in handy for someone else.