cicd 05--通过api调用jenkins job
1 介绍
笔者在 cicd 01 - cicd 04 中已经介绍了多种常见的jenkins流程, 和其创建的细节、注意事项。而在实际中,除了可以手动在前端触发流程外,偶尔也需要通过API来触发流程; 因此,本文基于之前的流程,完善了调用jenkins api 的案例。分享在此处以便于自己或者有需要的小伙伴查阅,后续会在此处持续更新jenkins api相关案例和注意事项。
2 api 案例
api 调用jenkins job可以分为2类,一类通过python api,另外也可以通过curl来实现,具体如下:
2.1 python api 调用
调用源码:
#!/usr/bin/python3
# -*- coding:utf-8 -*-
import logging
import pprint
import time
import jenkins
USER = 'yourJenkinsUserName'
PWD = 'yourPassword'
JENKINS_URL = "https://yourJenkinsUrl.com"
class JenkinsJob(object):
""""""
job_name = None
server = None
jenkins_url = None
def __init__(self, job_name=None):
self.login_jenkins(job_name)
def get_jenkins_url(self):
return self.jenkins_url
def login_jenkins(self, job_name=None):
"""
Login Jenkins and Get the jenkens object
"""
self.server = jenkins.Jenkins(
JENKINS_URL, username=USER, password=PWD
)
self.user = self.server.get_whoami()
self.version = self.server.get_version()
self.job_name = job_name
def get_next_build_number(self):
"""
Get next build number
"""
job_info = self.server.get_job_info(self.job_name)
next_build_num = job_info["nextBuildNumber"]
return next_build_num
def get_jenkins_url(self):
"""
Get Jenkins Build URL
"""
return self.jenkins_url
def build_job(self, dict_parameters, block_until_finish=True):
"""
Trigger the build of job
"""
job_name = self.job_name
next_build_num = self.get_next_build_number()
logging.info("start to trigger jenkins build %s: " % job_name)
logging.debug(dict_parameters)
self.server.build_job(job_name, dict_parameters)
build_number = next_build_num
# checking job is running
job_info = self.server.get_job_info(job_name)
last_build_number = 0
try:
last_build_number = job_info["lastBuild"]["number"]
except TypeError as e:
print("No job was built yet")
last_build_number = 0
self.jenkins_url = job_info["url"]
pprint.pprint(job_info)
while last_build_number < build_number:
time.sleep(10)
job_info = self.server.get_job_info(job_name)
last_build_number = job_info["lastBuild"]["number"]
build_number = last_build_number
build_info = self.server.get_build_info(job_name, build_number)
pprint.pprint(build_info)
if block_until_finish:
print("waiting the build job to be finished")
while build_info["building"]:
time.sleep(30)
build_info = self.server.get_build_info(job_name, last_build_number)
print("build is still running")
print("build is finished")
print("status: %s" % build_info["result"])
if build_info["result"] == "SUCCESS":
return True
else:
return False
else:
logging.info("don't waiting job to be finished")
self.jenkins_url = build_info.get("url", None)
logging.info("Jenkins url %s" % self.jenkins_url)
return True
def main(job_name, job_parameters):
"""
job_name: canoe_service
job_parameters: '{"action": action, "random": job_id }'
"""
jenkins_job = JenkinsJob(job_name)
jenkins_job.build_job(job_parameters)
if __name__ == "__main__":
job_name = 'deploy_kubectl_scale'
job_parameters = {'Cluster': 'data-pipeline', 'namespace': 'sre-test', 'deployment': 'xg-busybox-dev',
'replicas': 0}
main(job_name, job_parameters)
参数说明:
需要修改全局参数
USER = 'yourJenkinsUserName'
PWD = 'yourPassword'
填写job name 和参数
job_name 为实际的name即可;job_parameters 为dict 类型,参数和jenkins前端上的名称一致
job_name = 'deploy_kubectl_scale'
job_parameters = {'Cluster': 'data-pipeline', 'namespace': 'sre-test', 'deployment': 'xg-busybox-dev', 'replicas': 0}
注意: build_job(self, dict_parameters, block_until_finish=True) 中的 block_until_finish 默认为True,如果不想等待的话可以直接设置为False
输出结果:
/usr/bin/python3 /home/xg/files/code/gitlab/xghome/jenkins_api/app.py
{'_class': 'org.jenkinsci.plugins.workflow.job.WorkflowJob',
'actions': [{},
......
{}],
'artifacts': [],
'building': True,
'changeSets': [],
'culprits': [],
'description': 'data-pipeline sre-test/xg-busybox-dev 0',
'displayName': '#2',
'duration': 0,
'estimatedDuration': 4344,
'executor': {'_class': 'hudson.model.OneOffExecutor'},
'fullDisplayName': 'deploy_kubectl_scale #2',
'id': '2',
'keepLog': False,
'nextBuild': None,
'number': 2,
'previousBuild': {'number': 1,
'url': 'https://yourJenkinsUrl.com/job/deploy_kubectl_scale/1/'},
'queueId': 347380,
'result': None,
'timestamp': 1634634288223,
'url': 'https://yourJenkinsUrl.com/job/deploy_kubectl_scale/2/'}
waiting the build job to be finished
build is still running
build is finished
status: SUCCESS
2.2 curl api 调用
使用案例:
curl -d "token=yourToken&Cluster=data-pipeline&namespace=sre-test&deployment=xg-busybox-dev&replicas=0" -X POST https://yourJenkinsUrl.com/view/SRE/job/deploy_kubectl_scale/buildWithParameters
其中 -d “token=yourToken&Cluster=data-pipeline&namespace=sre-test&deployment=xg-busybox-dev&replicas=0” 为该请求的参数,其中token=yourToken 为固定的参数,其它的参数和流程前端上的参数一致。
若流程没有参数,那么就使用 JENKINS_URL/view/SRE/job/yourJenkinsJob/build?token=TOKEN_NAME 的url结构,也不需要 -d “参数” 等内容。
区别: 有参数的后缀为 buildWithParameters(?token=TOKEN_NAME, 这一部分可以移动到-d中), 没有参数的后缀为 build?token=TOKEN_NAME。
3 注意事项
- 本文调用的流程和 cicd 03–构建通用scale流程 相同,job_parameters 的参数也一一对应。
- 使用curl 的话需要注意是否有参数,有参数url末尾为 buildWithParameters?token=TOKEN_NAME ,没有参数 url 末尾为 build?token=TOKEN_NAME
- 使用curl 的话返回的信息及少,不便于作相关状态判断。