SoFunction
Updated on 2024-11-12

Python-jenkins: Getting Job Build Information

official document:

Requirement: When a job starts a build, get its build status. (Success, Failure, Dismissed, Building, Queuing)

Key Functions.

Get the result of whether the job is queued or not

Get the queue of jobs that are queued for construction, i.e., all the jobs in the pending state, if there are no jobs in the pending state, i.e., an empty list is returned.

queue_info = server.get_queue_info()

Getting job build results

server.get_build_info(name, build_number)[
      'result'] # End of build SUCCESS|FAILURE<class 'str'>  ABORTED <class 'str'> under constructionNone None <class 'NoneType'>

Code example.

def get_build_state(server, name, build_number):
  '''

  :param name: job_name
  :param build_number: ultimate1Sub-construction number
  :param:jenkins_server
  :return: ultimate1subconstructed state (computing) pending,success,false,building
  '''
  build_state = None

  # Get a queue of jobs that are queuing up for construction, i.e., all the jobs in the pending state, if there are no pending jobs, i.e., an empty list is returned.
  queue_info = server.get_queue_info()

  if queue_info:
    for queue_job_info in queue_info:
      if queue_job_info['task']['name'] == name:
        # msg = 'Pending, queue building'
        build_state = 'pending'
  else:

    build_state = server.get_build_info(name, build_number)[
      'result'] # End of build SUCCESS|FAILURE<class 'str'> ABORTED <class 'str'> Under construction None None <class 'NoneType'>
  return build_state

Encapsulate this functionality through an interface

@build_bp.route('/gotest/api/getBuildState', methods=['POST'])
def get_job_build_state():
  '''
    gainjobbuild state
    return:build_state Success,Faild,Pending,Building
    '''
  data = request.get_json()
  job_name = data['job_name']

  server = get_jenkins_server()
  # Get the last build number of the job
  lastbuildNumber = server.get_job_info(job_name)['lastBuild']['number']
  # Get build status
  build_state = get_build_state(server, job_name, lastbuildNumber)

  if build_state is None:
    build_msg = 'Building'
  elif build_state == 'SUCCESS':
    build_msg = 'SUCCESS'
  elif build_state == 'FAILURE':
    build_msg = 'FAILURE'
  elif build_state == 'ABORTED':
    build_msg = 'ABORTED'
  elif build_state =='pending':
    build_msg = 'pending'

  response = {}
  datas={}
  response['code'] = 200
  response['msg'] = 'OK'

  datas['build_state'] = build_msg
  datas['buildNumber'] = lastbuildNumber
  response['datas'] = datas

  return response

Test Interface.

import requests
url='http://127.0.0.1:5000/gotest/api/getBuildState'
data={'job_name':'android_official'}

r = (url,json=data)
print()

Response.

{"code":200,"datas":{"buildNumber":1010,"build_state":"SUCCESS"},"msg":"OK"}

Above this Python-jenkins get job build information way is all I share with you, I hope to give you a reference, and I hope you support me more.