#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "shuke"
# Date: 2018/1/17
from jenkinsapi.jenkins import Jenkins
from jenkinsapi.build import Build
def get_server_instance():
jenkins_url = 'http://127.0.0.1:8080/'
server = Jenkins(jenkins_url, username='admin', password='admin123')
return server
server = get_server_instance()
# 1. 版本
print(server.version)
'''
2.101
'''
# 2. 所有的job列表
print(server.keys())
print(server.get_jobs_list())
'''
['ansible-playbook', 'my-github']
'''
# 3. 全局信息查看
server.pprint()
'''
{'_class': 'hudson.model.Hudson',
'jobs': [{'_class': 'hudson.model.FreeStyleProject',
'color': 'blue',
'name': 'ansible-playbook',
'url': 'http://127.0.0.1:8080/job/ansible-playbook/'},
{'_class': 'hudson.model.FreeStyleProject',
'color': 'disabled',
'name': 'my-github',
'url': 'http://127.0.0.1:8080/job/my-github/'}]}
'''
# 3. 指定job的config.xml配置
print("my-github job config:\n", server['my-github'].get_config())
'''
my-github job config:
<?xml version='1.0' encoding='UTF-8'?>
<project>
<actions/>
<description></description>
<keepDependencies>false</keepDependencies>
<properties>
<com.coravy.hudson.plugins.github.GithubProjectProperty plugin="[email protected]">
<projectUrl>https://github.com/shuke163/CustAdmin.git/</projectUrl>
<displayName>Admin</displayName>
</com.coravy.hudson.plugins.github.GithubProjectProperty>
<jenkins.model.BuildDiscarderProperty>
<strategy class="hudson.tasks.LogRotator">
<daysToKeep>-1</daysToKeep>
<numToKeep>5</numToKeep>
<artifactDaysToKeep>-1</artifactDaysToKeep>
<artifactNumToKeep>-1</artifactNumToKeep>
</strategy>
</jenkins.model.BuildDiscarderProperty>
<hudson.model.ParametersDefinitionProperty>
<parameterDefinitions>
<hudson.model.ChoiceParameterDefinition>
<name>ip</name>
<description>ip</description>
<choices class="java.util.Arrays$ArrayList">
<a class="string-array">
<string>127.0.0.1</string>
</a>
</choices>
</hudson.model.ChoiceParameterDefinition>
</parameterDefinitions>
</hudson.model.ParametersDefinitionProperty>
</properties>
<scm class="hudson.scm.NullSCM"/>
<canRoam>true</canRoam>
<disabled>true</disabled>
<blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
<blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
<triggers/>
<concurrentBuild>false</concurrentBuild>
<builders>
<hudson.tasks.Shell>
<command>echo $ip</command>
</hudson.tasks.Shell>
</builders>
<publishers/>
<buildWrappers/>
</project>
'''
# 4. 得到的是一个包含所有jobs的生成器对象
print(server.get_jobs())
'''
['ansible-playbook', 'my-github']
'''
# 5. 所有的job描述
for job_name, job_instance in server.get_jobs():
print('Job Name:%s' % (job_instance.name))
print('Job Description:%s' % (job_instance.get_description()))
print('Is Job running:%s' % (job_instance.is_running()))
print('Is Job enabled:%s' % (job_instance.is_enabled()))
'''
Job Name:ansible-playbook
Job Description:ansible playbook
Is Job running:False
Is Job enabled:True
Job Name:my-github
Job Description:
Is Job running:False
Is Job enabled:True
'''
# 6. Disable/Enable a Jenkins Job
job_name = 'my-github'
if (server.has_job(job_name)):
job_instance = server.get_job(job_name)
job_instance.disable()
print('Name:%s,Is Job Enabled ?:%s' % (job_name, job_instance.is_enabled()))
'''
Name:my-github,Is Job Enabled ?:False
'''
# 7. CURD Job
server.create_job()
server.delete_job('ansible-playbook')
server.copy_job('my-job', 'new-my-job')
server.rename_job('my-github', 'new-my-github')
# 8. Get Plugin details
for plugin in server.get_plugins().values():
print("Short Name:%s" % (plugin.shortName))
print("Long Name:%s" % (plugin.longName))
print("Version:%s" % (plugin.version))
print("URL:%s" % (plugin.url))
print("Active:%s" % (plugin.active))
print("Enabled:%s" % (plugin.enabled))
'''
Short Name:jsch
Long Name:Jenkins JSch dependency plugin
Version:0.1.54.1
URL:http://wiki.jenkins-ci.org/display/JENKINS/JSch+plugin
Active:True
Enabled:True
Short Name:ws-cleanup
Long Name:Jenkins Workspace Cleanup Plugin
Version:0.34
URL:http://wiki.jenkins-ci.org/display/JENKINS/Workspace+Cleanup+Plugin
Active:True
Enabled:True
......
'''
# 9. 从已完成的构建中获取版本信息
def getSCMInfroFromLatestGoodBuild(url, jobName, username='admin', password='admin123'):
J = Jenkins(url, username, password)
job = J[jobName]
lgb = job.get_last_good_build()
return lgb.get_revision()
version = getSCMInfroFromLatestGoodBuild("http://127.0.0.1:8080/", 'ansible-playbook')
print(version)
'''
21c2b6ff6c842a86969f36f75424e17ae27eae68
'''
# 10. 其他
print(server.__dict__)
'''
{'username': 'admin', 'password': 'admin123', 'requester': <jenkinsapi.utils.requester.Requester object at 0x103423710>, 'lazy': False, 'jobs_container': None, '_data': {'_class': 'hudson.model.Hudson', 'jobs': [{'_class': 'hudson.model.FreeStyleProject', 'name': 'ansible-playbook', 'url': 'http://127.0.0.1:8080/job/ansible-playbook/', 'color': 'blue'}, {'_class': 'hudson.model.FreeStyleProject', 'name': 'my-github', 'url': 'http://127.0.0.1:8080/job/my-github/', 'color': 'disabled'}]}, 'baseurl': 'http://127.0.0.1:8080'}
'''
jobs = server.__dict__['_data']['jobs']
print(server.resolve_job_folders(jobs))
'''
[{'_class': 'hudson.model.FreeStyleProject', 'name': 'ansible-playbook', 'url': 'http://127.0.0.1:8080/job/ansible-playbook/', 'color': 'blue'}, {'_class': 'hudson.model.FreeStyleProject', 'name': 'my-github', 'url': 'http://127.0.0.1:8080/job/my-github/', 'color': 'disabled'}]
'''
# baseurl
print(server.baseurl)
'''
http://127.0.0.1:8080
'''
# username
print(server.username)
'''
admin
'''
# password
print(server.password)
'''
admin123
'''
# 判断job是否存在
print(server.has_job('prod-java'))
'''
False
'''
print(server.get_queue())
'''
http://127.0.0.1:8080/queue
'''
# 查看试图
print(server.views.keys())
'''
['My View', 'all', 'myview']
'''
# 删除试图
server.delete_view_by_url('http://127.0.0.1:8080/view/testview/')
# 获取最后一次构建
print(server['ansible-playbook'].get_last_good_build())
'''
ansible-playbook #27
'''
# BUILD构建相关
# 1. 构建(方式一)
params = {'Branch': 'oriin/master', 'host': '192.168.1.100'}
ret = server.build_job('ansible-playbook', params)
print(ret)
# 方式二
job = server['ansible-playbook']
run_job = job.invoke(build_params=params)
number = run_job.__dict__['_data']['executable']['number']
build_url = run_job.__dict__['_data']['executable']['url']
print("第%d次构建: %s" % (number, build_url))
'''
第40次构建: http://127.0.0.1:8080/job/ansible-playbook/40/
'''
# 结果查询
# 1. 方式一
job = server.get_job('ansible-playbook')
print(job.__dict__['_data']['builds'])
url = job.__dict__['_data']['lastBuild']['url']
number = job.__dict__['_data']['lastBuild']['number']
obj = Build(url, number, job)
# 2. 方式二
job = server['ansible-playbook']
url = job.__dict__['_data']['lastBuild']['url']
number = job.__dict__['_data']['lastBuild']['number']
obj = Build(url, number, job)
# 全局信息
print(obj.pprint())
'''
{'_class': 'hudson.model.FreeStyleBuild',
'actions': [{'_class': 'hudson.model.ParametersAction',
'parameters': [{'_class': 'net.uaznia.lukanus.hudson.plugins.gitparameter.GitParameterValue',
'name': 'Branch',
'value': 'oriin/master'},
{'_class': 'hudson.model.StringParameterValue',
'name': 'host',
'value': '192.168.1.100'}]},
{'_class': 'hudson.model.CauseAction',
'causes': [{'_class': 'hudson.model.Cause$UserIdCause',
'shortDescription': 'Started by user 管理员',
'userId': 'admin',
'userName': '管理员'}]},
{},
......
'''
print(obj.get_result_url())
'''
http://127.0.0.1:8080/job/ansible-playbook/40/testReport/api/python
'''
print(obj.is_running())
'''
False
'''
print(obj.stop())
'''
True
'''
print(obj.is_good())
'''
True
'''
print(obj.get_number())
print(obj.buildno)
'''
40
'''
print(obj.get_status())
'''
SUCCESS
'''
print(obj.get_revision())
'''
21c2b6ff6c842a86969f36f75424e17ae27eae68
'''
print(obj.get_revision_branch())
'''
[{'SHA1': '21c2b6ff6c842a86969f36f75424e17ae27eae68', 'name': 'refs/remotes/origin/master'}]
'''
print(obj.get_console())
'''
Started by user 管��
[EnvInject] - Loading node environment variables.
Building in workspace /Users/zhao/data/workspace/workspace/ansible-playbook
> /usr/local/bin/git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
> /usr/local/bin/git config remote.origin.url [email protected]:ansible-roles/zff.ansible.git # timeout=10
Fetching upstream changes from [email protected]:ansible-roles/zff.ansible.git
> /usr/local/bin/git --version # timeout=10
using GIT_SSH to set credentials deploy key
> /usr/local/bin/git fetch --tags --progress [email protected]:ansible-roles/zff.ansible.git +refs/heads/*:refs/remotes/origin/*
> /usr/local/bin/git rev-parse refs/remotes/origin/master^{commit} # timeout=10
> /usr/local/bin/git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10
Checking out Revision 21c2b6ff6c842a86969f36f75424e17ae27eae68 (refs/remotes/origin/master)
> /usr/local/bin/git config core.sparsecheckout # timeout=10
> /usr/local/bin/git checkout -f 21c2b6ff6c842a86969f36f75424e17ae27eae68
Commit message: "update tomcat root mode"
> /usr/local/bin/git rev-list --no-walk 21c2b6ff6c842a86969f36f75424e17ae27eae68 # timeout=10
[ansible-playbook] $ /bin/sh -xe /Users/Shared/Jenkins/tmp/jenkins280834745018509074.sh
+ echo 192.168.1.100
192.168.1.100
+ echo test
test
+ echo http://127.0.0.1:8080/job/ansible-playbook/40/
http://127.0.0.1:8080/job/ansible-playbook/40/
+ echo 40
40
+ echo jenkins-ansible-playbook-40
jenkins-ansible-playbook-40
Recording fingerprints
Finished: SUCCESS
'''
print(obj.get_causes())
'''
[{'_class': 'hudson.model.Cause$UserIdCause', 'shortDescription': 'Started by user 管理员', 'userId': 'admin', 'userName': '管理员'}]
'''
print(obj.get_params())
'''
{'Branch': 'oriin/master', 'host': '192.168.1.100'}
'''
print(obj.get_env_vars())
'''
{'BUILD_CAUSE': 'MANUALTRIGGER', 'BUILD_CAUSE_MANUALTRIGGER': 'true', 'BUILD_DISPLAY_NAME': '#40', 'BUILD_ID': '40', 'BUILD_NUMBER': '40', 'BUILD_TAG': 'jenkins-ansible-playbook-40', 'BUILD_URL': 'http://127.0.0.1:8080/job/ansible-playbook/40/', 'Branch': 'oriin/master', 'EXECUTOR_NUMBER': '1', 'HUDSON_HOME': '/Users/zhao/data/workspace', 'HUDSON_SERVER_COOKIE': '5634a2d507063d61', 'HUDSON_URL': 'http://127.0.0.1:8080/', 'JENKINS_HOME': '/Users/zhao/data/workspace', 'JENKINS_SERVER_COOKIE': '5634a2d507063d61', 'JENKINS_URL': 'http://127.0.0.1:8080/', 'JOB_BASE_NAME': 'ansible-playbook', 'JOB_NAME': 'ansible-playbook', 'JOB_URL': 'http://127.0.0.1:8080/job/ansible-playbook/', 'NODE_LABELS': 'master', 'NODE_NAME': 'master', 'ROOT_BUILD_CAUSE': 'MANUALTRIGGER', 'ROOT_BUILD_CAUSE_MANUALTRIGGER': 'true', 'RUN_CHANGES_DISPLAY_URL': 'http://127.0.0.1:8080/job/ansible-playbook/40/display/redirect?page=changes', 'RUN_DISPLAY_URL': 'http://127.0.0.1:8080/job/ansible-playbook/40/display/redirect', 'TEST_ARGS': 'test', 'host': '192.168.1.100'}
'''
print(obj.job)
'''
ansible-playbook
'''
print(obj.get_data('http://127.0.0.1:8080/job/ansible-playbook/40/api/python/?pretty=true'))
{'_class': 'hudson.model.FreeStyleBuild', 'actions': [{'_class': 'hudson.model.ParametersAction', 'parameters': [{'_class': 'net.uaznia.lukanus.hudson.plugins.gitparameter.GitParameterValue', 'name': 'Branch', 'value': 'oriin/master'}, {'_class': 'hudson.model.StringParameterValue', 'name': 'host', 'value': '192.168.1.100'}]}, {'_class': 'hudson.model.CauseAction', 'causes': [{'_class': 'hudson.model.Cause$UserIdCause', 'shortDescription': 'Started by user 管理员', 'userId': 'admin', 'userName': '管理员'}]}, {}, {'_class': 'hudson.plugins.git.util.BuildData', 'buildsByBranchName': {'refs/remotes/origin/master': {'_class': 'hudson.plugins.git.util.Build', 'buildNumber': 40, 'buildResult': None, 'marked': {'SHA1': '21c2b6ff6c842a86969f36f75424e17ae27eae68', 'branch': [{'SHA1': '21c2b6ff6c842a86969f36f75424e17ae27eae68', 'name': 'refs/remotes/origin/master'}]}, 'revision': {'SHA1': '21c2b6ff6c842a86969f36f75424e17ae27eae68', 'branch': [{'SHA1': '21c2b6ff6c842a86969f36f75424e17ae27eae68', 'name': 'refs/remotes/origin/master'}]}}}, 'lastBuiltRevision': {'SHA1': '21c2b6ff6c842a86969f36f75424e17ae27eae68', 'branch': [{'SHA1': '21c2b6ff6c842a86969f36f75424e17ae27eae68', 'name': 'refs/remotes/origin/master'}]}, 'remoteUrls': ['[email protected]:ansible-roles/zff.ansible.git'], 'scmName': ''}, {'_class': 'hudson.plugins.git.GitTagAction'}, {}, {}, {}, {}, {}], 'artifacts': [], 'building': False, 'description': None, 'displayName': '#40', 'duration': 735, 'estimatedDuration': 897, 'executor': None, 'fullDisplayName': 'ansible-playbook #40', 'id': '40', 'keepLog': False, 'number': 40, 'queueId': 21, 'result': 'SUCCESS', 'timestamp': 1516172959444, 'url': 'http://127.0.0.1:8080/job/ansible-playbook/40/', 'builtOn': '', 'changeSet': {'_class': 'hudson.plugins.git.GitChangeSetList', 'items': [], 'kind': 'git'}, 'culprits': []}