Skip to content

Get Job Executions in Rundeck

October 2nd, 2018 - ITTutorial(1 min)

Following the previous articles, we are now in position to query job executions. The query is done via API as well. As a job can have an arbitrary number of executions, it’s advisable to use pagination.

The code follows the same lines as the one in the previous entries:

# API call to get the list of the executions for a Job.
SIZE = 100
def getExecutionsForAJob(server, port, api_key, job_id, page=0, size=SIZE):
    url =  server +':'+port + \
        '/api/1/job/'+job_id + \
        '/executions?max='+('%d' % size) + \
        '&offset='+('%d' % (page * size))
    log.info(url)
    headers = {'Content-Type': 'application/json','X-RunDeck-Auth-Token': api_key }
    r = requests.get(url, headers=headers, verify=False)
    return r.text.encode('utf-8')

This function builds the URL for the call and returns an XML string. Its parameters are:

  • server - the rundeck server
  • port - the rundeck server’s port
  • api_key - the api key for rundeck
  • job_id - one of the job IDs obtained by calling functions described here (or hardcoded)
  • page - the page we want to retrieve (offset is size * pages)
  • size - the page size (aka the max number of executions we want to retrieve at once)

We can go a step further with a wrapper:

MAXCOUNT=1000
PAGE=0

def getAllExecutionsForAJob(server, port, api_key, jobid, maxCount=sys.maxsize):
    executions = {}
    count = 1
    page = PAGE
    while count and page < maxCount + PAGE:
        batch = getExecutionDate(getExecutionsForAJob(
            server, port, api_key, jobid, page))
        count = len(batch)
        offset += count
        if count:
            executions.update(batch)
    return executions

…which would build a list of maximum MAXCOUNT * SIZE executions.

As the end objective is to remove old jobs, we need to retrieve the date for each execution. In effect we only need the execution ID and date:

# Returns a dict
# {
#   'execution_id01': 'execution_date01',
#   'execution_id02': 'execution_date02',
#   ...
# }
def getExecutionDate(executionsinfo_xml):
    execid_dates = {}
    root = ET.fromstring(executionsinfo_xml)
    for executions in root:
        for execution in executions.findall('execution'):
            execution_id = execution.get('id')
            for date in execution.findall('date-ended'):
                execution_date = date.get('unixtime')
            execid_dates[execution_id] = execution_date
    return execid_dates

In order to retrieve the executions with dates we’d need to call something like:

getExecutionDate(
  getExecutionsForAJob(server, port, api_key, jobid, page)
)

HTH,

Share on
Reddit
Linked in
Whatsapp

A little experiment: