user2439278
user2439278

Reputation: 1214

How to parse and update jenkins job config.xml using python jenkinsapi module

I have installed Jenkinsapi python module and created below python script.

from jenkinsapi.jenkins import Jenkins
jenkinsSource = 'http://10.52.123.124:8080/'
server = Jenkins(jenkinsSource, username = 'XXXXX', password = 'YYYYY')
myJob=server.get_job("__test")
myConfig=myJob.get_config()
print myConfig

Now I need to parse the XML from the variable myConfig and fetch the value given for triggers (cron entry) and save it to another variable in python. So that I can replace the cron entry using jenkinsapi module.

Upvotes: 1

Views: 4117

Answers (1)

user481572
user481572

Reputation:

You can read myConfig with xpath, see code below which reads numToKeep from hudson.tasks.LogRotator. This prints out jobs whose build retention is set to more than 10 in Discard old builds job configuration.

Calling code

jobs = server.get_jobs()

for job in jobs:
    full_name = job['fullname']
    config = server.get_job_config(full_name)
    num_days = h.get_value_from_string(config, key='.//numToKeep')
    if num_days > 10:
        print(full_name, num_days)

Helper function which reads property from config

import xml.etree.ElementTree as ET

def get_value_from_string(xml_string, key):
    parsed = ET.fromstring(xml_string)
    find_result = parsed.findall(key)

    value = 0
    if len(find_result) > 0:
        value = int(find_result[0].text)

    return value

To update a jobs configuration

config = server.get_job_config('<the_job>')
old_config_part = '<numToKeep>100</numToKeep>'
new_config_part = '<numToKeep>5</numToKeep>'
new_config = config.replace(old_config_part, new_config_part)
server.reconfig_job(full_name, new_config)

Upvotes: 2

Related Questions