如何在Python中使用Jenkins API进行前后构建步骤?

时间:2015-04-30 05:47:21

标签: python api jenkins

我正在使用Jenkins Python API并希望自动执行前后构建步骤。我怎样才能做到这一点?

我能够连接到我的Jenkins服务器并列出所有构建和插件,但是如何使用Python Jenkins API自动化前后构建步骤?

1 个答案:

答案 0 :(得分:0)



您说过要 “自动化构建前和构建后步骤”
通过这种方式,我假设您的意思是要自动向现有作业中添加构建前和构建后步骤?

为此,通常我必须查看此URL上的作业的config.xml: http://<IP_of_jenkins_instance>:8080/job/<JOB_NAME>/config.xml

然后我弄清楚需要在哪里插入pre / post构建步骤,相应地进行拆分,然后上传新的作业配置。

例如,下面的示例将插入并执行“ Execute Shell”构建步骤(作为第一个构建步骤!),并显示“ hello”。

import requests


from jenkinsapi.jenkins import Jenkins
from jenkinsapi.utils.requester import Requester


USERNAME, PASSWORD = '<USERNAME>', '<PASSWORD>'
JK = 'http://<IP of jenkins instance>:8080'


def jenkins_instance(jenkins):

    requests.packages.urllib3.disable_warnings()
    return Jenkins(jenkins, requester=Requester(USERNAME, PASSWORD, baseurl=jenkins, ssl_verify=False, timeout=20))


def _get_config_given_job(server, job_name):

    config = server.get_job(job_name).get_config().encode('utf-8')
    return config


def _upload_new_job_config(job_name, config):

    url = '{0}/job/{1}/config.xml'.format(JK, job_name)
    r = requests.post(url, data=config, auth=(USERNAME, PASSWORD))
    if str(r.status_code).startswith('2'):
        print 'Successfully updated config for:' + job_name


def main():

    job_name = '<YOUR JOB NAME>'
    server = jenkins_instance(JK)
    config = _get_config_given_job(server, job_name)
    shell_build_step = '<hudson.tasks.Shell><command>echo hello</command></hudson.tasks.Shell>'
    new_config = '{0}{1}{2}{3}'.format(
        config.split('<builders>')[0],
        '<builders>',
        shell_build_step,
        config.split('<builders>')[1]
    )
    _upload_new_job_config(job_name, new_config)


if __name__ == '__main__':
    main()