使用JenkinsApi::Client获取Folder下的job

一般来说使用JenkinsAPI可以通过点击右下角的Rest API 就可以了

REST API

Many objects of Jenkins provide the remote access API. They are available at /.../api/ where "..." portion is the object for which you'd like to access.

XML API

Access data exposed in HTML as XML for machine consumption. Schema is also available.

You can also specify optional XPath to control the fragment you'd like to obtain (but see below). For example, ../api/xml?xpath=/*/*[0].

For XPath that matches multiple nodes, you need to also specify the "wrapper" query parameter to specify the name of the root XML element to be create so that the resulting XML becomes well-formed.

Similarly exclude query parameter can be used to exclude nodes that match the given XPath from the result. This is useful for trimming down the amount of data you fetch (but again see below). This query parameter can be specified multiple times.

XPath filtering is powerful, and you can have it only return a very small data, but note that the server still has to build a full DOM of the raw data, which could cause a large memory spike. To avoid overloading the server, consider using the tree parameter, or use the xpath parameter in conjunction with the tree parameter. When used together, the result of the tree parameter filtering is built into DOM, then the XPath is applied to compute the final return value. In this way, you can often substantially reduce the size of DOM built in memory.

但是有些情况下需要用到JenkinsApi::Client 官网连接Class: JenkinsApi::Client — Documentation for jenkins_api_client (1.5.3) icon-default.png?t=M3C8https://www.rubydoc.info/gems/jenkins_api_client/1.5.3/JenkinsApi/Client首先感受一下它的参数:

VALID_PARAMS =
Parameters that are permitted as options while initializing the client

[
  "server_url",
  "server_ip",
  "server_port",
  "proxy_ip",
  "proxy_port",
  "proxy_protocol",
  "jenkins_path",
  "username",
  "password",
  "password_base64",
  "logger",
  "log_location",
  "log_level",
  "timeout",
  "http_open_timeout",
  "http_read_timeout",
  "ssl",
  "follow_redirects",
  "identity_file",
  "cookies"
].freeze

使用也很简单:

@client = JenkinsApi::Client.new(
  :server_url => 'https://example.org',
  :username   => 'jhoblitt',
  :password   => '...',
  #:log_level  => Logger::DEBUG,
)

获取job可以使用这个:Class: JenkinsApi::Client::Job — Documentation for jenkins_api_client (1.5.3) icon-default.png?t=M3C8https://www.rubydoc.info/gems/jenkins_api_client/1.5.3/JenkinsApi/Client/Job

一般常用的方法都有介绍,但是怎么获取folder下面的job呢?参考这个链接:https://gist.github.com/jhoblitt/5f812cba39f0ec3c2e01f00d97d379a2icon-default.png?t=M3C8https://gist.github.com/jhoblitt/5f812cba39f0ec3c2e01f00d97d379a2直接粘贴原文代码过来,需要的可以根据内容自取,亲测好用,就不贴自己的代码了。

#!/usr/bin/env ruby

require 'benchmark'
require 'jenkins_api_client'
require 'json'

@client = JenkinsApi::Client.new(
  :server_url => 'https://example.org',
  :username   => 'jhoblitt',
  :password   => '...',
  #:log_level  => Logger::DEBUG,
)

def api
  def find_jobs(jobs, folder_path = nil)
    # path should not have a leading `/`
    found = []

    jobs.each do |job|
      name = job['name']
      if folder_path
        # add folder path to job name
        name = "#{folder_path}/#{job['name']}"
        job['name'] = name
      end

      found << job

      if job['_class'] == 'com.cloudbees.hudson.plugins.folder.Folder'
        # mangle "folder" path into "API" path
        api_path = '/job/' + name.split('/').join('/job/')
        folder = @client.api_get_request(api_path, "tree=jobs[name]")["jobs"]
        found += find_jobs(folder, name)
      end
    end

    found
  end

  jobs = @client.api_get_request("", "tree=jobs[name]")["jobs"]
  find_jobs(jobs)
end

def groovy
  # based on groovy code I hacked together for recursively listing jobs/folders
  # for the puppet jenkins module
  # https://github.com/jenkinsci/puppet-jenkins/blob/master/files/puppet_helper.groovy
  text = @client.exec_script(<<'EOS')
    def Map findJobs(Object obj, String namespace = null) {
      def found = [:]
      // groovy apparently can't #collect on a list and return a map?
      obj.items.each { job ->
        // a possibly better approach would be to walk the parent chain from //
        // each job
        def path = job.getName()
        if (namespace) {
          path = "${namespace}/" + path
        }
        found[path] = job
        // intentionally not using `instanceof` here so we don't blow up if the
        // cloudbees-folder plugin is not installed
        if (job.getClass().getName() == 'com.cloudbees.hudson.plugins.folder.Folder') {
          found << findJobs(job, path)
        }
      }
      found
    }
    void job_list_json() {
      def jobs = findJobs(Jenkins.getInstance())
      def allInfo = jobs.collect { path, job ->
        // at least these job classes do not respond to respond to #isDisabled:
        // - org.jenkinsci.plugins.workflow.job.WorkflowJob
        // - com.cloudbees.hudson.plugins.folder.Folder
        def enabled = false
        if (job.metaClass.respondsTo(job, 'isDisabled')) {
          enabled = !job.isDisabled()
        }
        [
          _class: job.getClass().toString(),
          name: path,
        ]
      }
      def builder = new groovy.json.JsonBuilder(allInfo)
      out.println(builder.toPrettyString())
    }
    job_list_json()
EOS

  JSON.parse(text)
end

n = 10
Benchmark.bmbm do |x|
  x.report('api:')   { n.times { api } }
  x.report('groovy:')  { n.times { groovy } }
end

benchmark_output.txt

Rehearsal -------------------------------------------
api:      0.360000   0.070000   0.430000 ( 33.993842)
groovy:   0.060000   0.010000   0.070000 (  4.433300)
---------------------------------- total: 0.500000sec

              user     system      total        real
api:      0.340000   0.080000   0.420000 ( 31.899548)
groovy:   0.060000   0.000000   0.060000 (  4.385597)

jobs.txt

# example output showing the number of jobs/folders on the jenkins instance the benchmark was run against

{"name"=>"backup", "_class"=>"class com.cloudbees.hudson.plugins.folder.Folder"}
{"name"=>"backup/build-sqre-github-snapshot", "_class"=>"class org.jenkinsci.plugins.workflow.job.WorkflowJob"}
{"name"=>"backup/jenkins-ebs-snapshot", "_class"=>"class hudson.model.FreeStyleProject"}
{"name"=>"backup/nightly-sqre-github-snapshot", "_class"=>"class org.jenkinsci.plugins.workflow.job.WorkflowJob"}
{"name"=>"ci-ci", "_class"=>"class com.cloudbees.hudson.plugins.folder.Folder"}
{"name"=>"ci-ci/jenkins-dm-jobs", "_class"=>"class hudson.model.FreeStyleProject"}
{"name"=>"ci-ci/test-freestyle", "_class"=>"class hudson.model.FreeStyleProject"}
{"name"=>"ci-ci/test-pipeline", "_class"=>"class org.jenkinsci.plugins.workflow.job.WorkflowJob"}
{"name"=>"ci-ci/test-pipeline-docker", "_class"=>"class org.jenkinsci.plugins.workflow.job.WorkflowJob"}
{"name"=>"ci-ci/test-pipeline-write", "_class"=>"class org.jenkinsci.plugins.workflow.job.WorkflowJob"}
{"name"=>"ci_hsc", "_class"=>"class hudson.model.FreeStyleProject"}
{"name"=>"cowboy", "_class"=>"class com.cloudbees.hudson.plugins.folder.Folder"}
{"name"=>"cowboy/stack", "_class"=>"class org.jenkinsci.plugins.workflow.job.WorkflowJob"}
{"name"=>"dax_webserv", "_class"=>"class hudson.model.FreeStyleProject"}
{"name"=>"lsst_apps", "_class"=>"class hudson.model.FreeStyleProject"}
{"name"=>"lsst_distrib", "_class"=>"class hudson.model.FreeStyleProject"}
{"name"=>"lsst_py3", "_class"=>"class hudson.model.FreeStyleProject"}
{"name"=>"lsst_sims", "_class"=>"class hudson.model.FreeStyleProject"}
{"name"=>"qserv", "_class"=>"class com.cloudbees.hudson.plugins.folder.Folder"}
{"name"=>"qserv/docker", "_class"=>"class com.cloudbees.hudson.plugins.folder.Folder"}
{"name"=>"qserv/docker/build", "_class"=>"class org.jenkinsci.plugins.workflow.job.WorkflowJob"}
{"name"=>"qserv_distrib", "_class"=>"class hudson.model.FreeStyleProject"}
{"name"=>"release", "_class"=>"class com.cloudbees.hudson.plugins.folder.Folder"}
{"name"=>"release/build-publish-tag", "_class"=>"class org.jenkinsci.plugins.workflow.job.WorkflowJob"}
{"name"=>"release/docker", "_class"=>"class com.cloudbees.hudson.plugins.folder.Folder"}
{"name"=>"release/docker/build", "_class"=>"class org.jenkinsci.plugins.workflow.job.WorkflowJob"}
{"name"=>"release/docker/newinstall", "_class"=>"class org.jenkinsci.plugins.workflow.job.WorkflowJob"}
{"name"=>"release/docker/prepare", "_class"=>"class org.jenkinsci.plugins.workflow.job.WorkflowJob"}
{"name"=>"release/run-publish", "_class"=>"class hudson.model.FreeStyleProject"}
{"name"=>"release/run-rebuild", "_class"=>"class hudson.model.FreeStyleProject"}
{"name"=>"release/tag-git-repos", "_class"=>"class hudson.model.FreeStyleProject"}
{"name"=>"release/weekly-release", "_class"=>"class org.jenkinsci.plugins.workflow.job.WorkflowJob"}
{"name"=>"seeds", "_class"=>"class com.cloudbees.hudson.plugins.folder.Folder"}
{"name"=>"seeds/dm-jobs", "_class"=>"class hudson.model.FreeStyleProject"}
{"name"=>"sims_utils", "_class"=>"class hudson.model.FreeStyleProject"}
{"name"=>"stack-os-matrix", "_class"=>"class hudson.matrix.MatrixProject"}
{"name"=>"stack-osx", "_class"=>"class hudson.matrix.MatrixProject"}
{"name"=>"validate_drp", "_class"=>"class hudson.matrix.MatrixProject"}

你可能感兴趣的:(ruby,on,rails,ruby,on,rails)