How to get trigger information in Jenkins programmatically

I need to add the next build time planned in the build email after the build in Jenkins.

The trigger can be " Build periodically" or " Poll SCM" or anything with a schedule.

I know that trigger information is in the config.xml file, for example.

<triggers>
    <hudson.triggers.SCMTrigger>
      <spec>8 */2 * * 1-5</spec>
      <ignorePostCommitHooks>false</ignorePostCommitHooks>
    </hudson.triggers.SCMTrigger>
  </triggers>

and I also know how to get the trigger type and specification using custom scripts from the config.xml file and calculate the next build time.

I wonder if the Jenkins API has to expose this information out of the box. I searched but found nothing.

+4
source share
1 answer

, , , , , script, Jenkins :

#!groovy

Jenkins.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()}")
  }
}

, SCM, ( cron , , ), post-commit.

script, JSON :

#!groovy
import 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()

Jenkins script -API, HTTP-.

, curl , script :

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

Jenkins , -u <USERNAME>:<PASSWORD>.

:

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

. , , , , - .

+1

Source: https://habr.com/ru/post/1676932/


All Articles