def __init__(self, username, token): self.j = jenkins.Jenkins(JENKINS_IP, username, token)
service_file = open( '/temp/output/{0}_{1}/service'.format(service, build_number), 'wb') service_file.write(service) service_file.close() service_file = open('/temp/found_info', 'wb') service_file.write(" ") service_file.close() ## # START MAIN FUNCTION ## print('HELLO') print('1. Create connection...') try: server = jenkins.Jenkins(url=URL, username=USERNAME, password=PASSWORD) except: print("Connection isn't create!") start() print('3. Get all services from data.json') jobs_data_file = open('/opt/data.json') services_dict = json.load(jobs_data_file) pprint(services_dict) # # jobs_data_file = open('/opt/build.json') build_data = json.load(jobs_data_file)
# -*- coding: UTF-8 -*- import jenkins server = jenkins.Jenkins('http://django2.example.com:8080/jenkins/', username='******', password='******') jobs = server.get_jobs() # 默认我的任务是不存在的。 job_name = 'empty' job_name_exist_flag = server.get_job_name(job_name) if job_name_exist_flag is None: print('[INFO] %s does not exist then create it.' % job_name) server.create_job('empty', jenkins.EMPTY_CONFIG_XML) else: print('[INFO] %s exists and ignore creating job.' % job_name) print('[INFO] %s job info:' % job_name) print(server.get_job_info(job_name)) # print('[INFO] %s job enviornment:' % job_name) # print(server.get_build_env_vars(job_name, 0)) # print('[INFO] All the jobs:') # print(jobs) # 获取我的任务xml配置信息。 print('\n') job_conf = server.get_job_config('empty') print(job_conf)
import os import jenkins import time import random try: print("\033[1;32mEnter path to the repo: \033[1;m", end = '') path_to_repo = input() print("\033[1;32mEnter the name of the project: \033[1;m", end = '') project_name = input() server = jenkins.Jenkins('http://localhost:8080', username='******', password='******') jobs = server.get_all_jobs() last_build_number = 0 try: last_build_number = server.get_job_info(project_name)['lastCompletedBuild']['number'] except expression as identifier: print("No builds might have been started yet on this job!\n") print("\nNo of builds on this job for the repo as of now: " + str(last_build_number)+"\n") num = random.randint(1,9999) os.system("cd " + path_to_repo + "; touch "+str(num)+".txt ; git add --all ; git commit -m \"test\" ; git push gitlab ") print("\nWaiting for few seconds for the build to get triggered...\n") time.sleep(40) latest_build_number = server.get_job_info(project_name)['lastCompletedBuild']['number']
import jenkins j = jenkins.Jenkins("http://localhost:8080", "admin", "admin") items = ["Development", "NewDev-1", "Testing"] i = 0 while i < len(items): j.build_job('%s' % items[i]) i = i + 1
{...} """ # the last 100 jobs are returned by default. depth=1 is so build objects are populated builds = server.get_job_info(job, depth=1)["builds"] for build in builds: build_commit = next( (action["lastBuiltRevision"]["SHA1"] for action in build["actions"] if "lastBuiltRevision" in action), None) if build_commit == commit: return build return None server = jenkins.Jenkins(jenkins_host, username=jenkins_user, password=jenkins_password) job = "%s/%s" % (multibranch_job, branch) print("Waiting to find build…") start = datetime.datetime.now() build = None while True: try: build = find_build(job, commit) except (exceptions.RequestException, jenkins.JenkinsException): pass if build: break sleep(10)
def start_service(): j = jenkins.Jenkins('http://192.168.1.111:8080', username='******', password='******') return j
def test_custom_timeout(self): j = jenkins.Jenkins('{0}'.format(self.base_url), timeout=300) self.assertEqual(j.timeout, 300)
def check_queue(): """ Specifically checks for the status of the Jenkins queue. The docs are sparse here, but ``jenkins/core/src/main/resources/hudson/model/queue/CauseOfBlockage`` has the specific reasons this check needs: * *BecauseLabelIsBusy* Waiting for next available executor on {0} * *BecauseLabelIsOffline* All nodes of label \u2018{0}\u2019 are offline * *BecauseNodeIsBusy* Waiting for next available executor on {0} * *BecauseNodeLabelIsOffline* There are no nodes with the label \u2018{0}\u2019 * *BecauseNodeIsOffline* {0} is offline The distinction is the need for a label or a node. In the case of a node, it will get matched directly to the nodes in the configuration, in case of a label it will go through the configured nodes and pick the first matched to its labels. Label needed example -------------------- Jenkins queue reports that 'All nodes of label x86_64 are offline'. The configuration has:: nodes: { 'centos6': { ... 'labels': ['x86_64', 'centos', 'centos6'] } } Since 'x86_64' exists in the 'centos6' configured node, it will be sent off to create that one. Node needed example ------------------- Jenkins reports that 'wheezy is offline'. The configuration has a few labels configured:: nodes: { 'wheezy': { ... } 'centos6': { ... } } Since the key 'wheezy' matches the node required by the build system to continue it goes off to create it. """ jenkins_url = pecan.conf.jenkins['url'] jenkins_user = pecan.conf.jenkins['user'] jenkins_token = pecan.conf.jenkins['token'] conn = jenkins.Jenkins(jenkins_url, jenkins_user, jenkins_token) result = conn.get_queue_info() needed_nodes = {} if result: for task in result: if task['why'] is None: # this may happen when multiple tasks are getting pilled up (for a PR for example) # and there is no 'why' yet. So the API has a `None` for it which would break logic # to infer what is needed to get it unstuck continue if util.is_stuck(task['why']): logger.info('found stuck task with name: %s' % task['task']['name']) logger.info('reason was: %s' % task['why']) node_name = util.match_node(task['why']) if not node_name: # this usually happens when jenkins is waiting on an executor # on a static slave whose labels are not a subset of a # node in the mita config logger.warning('unable to match a suitable node') logger.warning('will infer from job labels') job_url = task['task']['url'] job_name = util.job_from_url(job_url) try: conn.get_job_info(job_name) logger.info("Job info found for: %s", job_name) node_name = util.match_node_from_job_config(job_url) except jenkins.NotFoundException: logger.warning('No job info found for: %s', job_name) logger.warning('Will assume the job is a matrix job') node_name = util.match_node_from_matrix_job_name( job_name) if not node_name: logger.warning( 'completely unable to match a node to provide') continue logger.info('inferred node as: %s' % str(node_name)) if node_name: logger.info('matched a node name to config: %s' % node_name) # TODO: this should talk to the pecan app over HTTP using # the `app.conf.pecan_app` configuration entry, and then follow this logic: # * got asked to create a new node -> check for an entry in the DB for a node that # matches the characteristics of it. # * if there is one already: # - check that if it has been running for more than N (configurable) minutes (defaults to 8): # * if it has, it means that it is probable busy already, so: # - create a new node in the cloud backend matching the characteristics needed # * if it hasn't, it means that it is still getting provisioned so: # - skip - do a log warning # * if there is more than one, and it has been more than # N (8) minutes since they got launched it is possible # that they are configured *incorrectly* and we should not # keep launching more, so log the warning and skip. # - now ask Jenkins about machines that have been idle # for N (configurable) minutes, and see if matches # a record in the DB for the characteristics that we are # being asked to create. # * if found/matched: # - log the warnings again, something is not working right. if needed_nodes.get(node_name): needed_nodes[node_name] += 1 else: needed_nodes[node_name] = 1 else: logger.warning( 'could not match a node name to config for labels') else: logger.info('no tasks where fund in "stuck" state') elif result == []: logger.info('the Jenkins queue is empty, nothing to do') else: logger.warning('attempted to get queue info but got: %s' % result) # At this point we might have a bag of nodes that we need to create, go over that # mapping and ask as many as Jenkins needs: node_endpoint = get_mita_api('nodes') for node_name, count in needed_nodes.items(): configured_node = pecan.conf.nodes[node_name] configured_node['name'] = node_name configured_node['count'] = count requests.post(node_endpoint, data=json.dumps(configured_node))
def test_without_user_or_password(self): j = jenkins.Jenkins('{0}'.format(self.base_url)) j._maybe_add_auth() self.assertEqual(j.server, self.make_url('')) self.assertEqual(j.auth, None) self.assertEqual(j.crumb, None)
def test_default_timeout(self): j = jenkins.Jenkins('{0}'.format(self.base_url)) self.assertEqual(j.timeout, socket._GLOBAL_DEFAULT_TIMEOUT)
def test_wait_for_normal_op__negative_timeout(self): j = jenkins.Jenkins('http://example.com', 'test', 'test') with self.assertRaises(ValueError) as context_manager: j.wait_for_normal_op(-1) self.assertEqual(str(context_manager.exception), "Timeout must be >= 0 not -1")
def test_wait_for_normal_op__empty_response(self, version_mock, jenkins_mock): j = jenkins.Jenkins('http://example.com', 'test', 'test') self.assertFalse(j.wait_for_normal_op(0))
def test_wait_for_normal_op(self, version_mock, jenkins_mock): j = jenkins.Jenkins('http://example.com', 'test', 'test') self.assertTrue(j.wait_for_normal_op(0))
def __init__(self,jsever_obj): self.server = jenkins.Jenkins(jsever_obj.api_url, username=jsever_obj.username, password=jsever_obj.token) self.jsever_obj = jsever_obj
import jenkins jenkins_server_url = 'http://jenkins.ci.snsshop.net' jenkins_url = 'http://10.100.100.131:8080' user_id = 'jk_test' api_token = '76547d8b7a3e3022aeb02833c2a5fcb0' api_job = 'Debug/apitest' debug_job = 'Debug/debug' server = jenkins.Jenkins(jenkins_url, username=user_id, password=api_token) print('Jenkins Version:%s' % server.get_version()) user = server.get_whoami() print('User: %s' % user['fullName']) # get jobs def show_jobs(): jobs = server.get_jobs(folder_depth=1) print(jobs) for job in jobs: print('Job: ', job) # create job def create_job(job_name): server.create_job(job_name, jenkins.EMPTY_FOLDER_XML) # build job #server.build_job(api_job,{'SRV_NAME': 'service-order'}) #server.build_job(debug_job)
from flask_wtf.csrf import CSRFProtect from flask_sqlalchemy import SQLAlchemy from ButterSalt.saltapi import SaltApi app = Flask(__name__) app.config.from_object('config') bootstrap = Bootstrap(app) moment = Moment(app) CSRFProtect(app) db = SQLAlchemy(app) salt = SaltApi(app.config.get('SALT_API'), app.config.get('USERNAME'), app.config.get('PASSWORD')) J_server = jenkins.Jenkins(app.config.get('JENKINS_API'), username=app.config.get('J_USERNAME'), password=app.config.get('J_PASSWORD')) from ButterSalt.views.cmdb import cmdb from ButterSalt.views.saltstack import saltstack from ButterSalt.views.user import user from ButterSalt.views.deployment import deployment from ButterSalt.views.home import home app.register_blueprint(cmdb) app.register_blueprint(saltstack) app.register_blueprint(user) app.register_blueprint(deployment) app.register_blueprint(home) @app.errorhandler(404)
so_condition_1 = condition['so_condition_1'] so_qualifier = condition['so_qualifier'] so_condition_2 = condition['so_condition_2'] sub_condition = '({} {} {})'.format( so_condition_1, so_qualifier, so_condition_2) condition_text.append(sub_condition) et.SubElement(phase_job, 'enableCondition').text = 'true' et.SubElement( phase_job, 'condition').text = ' && '.join(condition_text) else: et.SubElement(phase_job, 'condition') # export Jenkins config file jenkins_job_config = et.tostring(project, xml_declaration=True, encoding='UTF-8', pretty_print=True) print(jenkins_job_config) # ********************************* # import config directly to Jenkins # ********************************* server = jenkins.Jenkins(args.jenkins_url, username=args.jenkins_username, password=args.jenkins_token) server.create_job(exp_json['so_job_table']['so_module'], jenkins_job_config)
def jenkins_server(self): # server = jenkins.Jenkins(self.rootURL, username=self.userName, password=self.password) name = 'admin' token = 'ef6b51132237b4b14f5de8b025b1c844' server = jenkins.Jenkins('http://192.168.16.221:8080/jenkins', name, token) return server
#coding:utf-8 """ 例子添加、配置、启动和删除Jenkins 节点 """ import jenkins server = jenkins.Jenkins('http://192.168.204.128:8080', username='******', password='******') server.create_node('slave1') nodes = server.get_nodes() print(nodes) # node_config = server.get_node_info('slave1') # print(node_config) # server.disable_node('slave1') # server.enable_node('slave1') # # # create node with parameters params = { 'port': '22', 'username': '******', 'credentialsId': '10f3a3c8-be35-327e-b60b-a3e5edb0e45f', 'host': 'my.jenkins.slave1' } server.create_node('slave1', nodeDescription='my test slave', remoteFS='/home/juser', labels='precise', exclusive=True, launcher=jenkins.LAUNCHER_SSH,
def __init__(self, username='******', password='******'): self._url = 'http://10.128.10.10:8080/' self._username = username self._password = password self.get_server = jenkins.Jenkins(self._url, username=self._username, password=self._password)
SPDX-License-Identifier: Apache-2.0 Third-Party Code: This code may depend on other components under separate copyright notice and license terms. Your use of the source code for those components is subject to the terms and conditions of the respective license as noted in the Third-Party source code file. ******************************************************** """ import os import jenkins import string import sys from jenkinsapi.jenkins import Jenkins jenkins_host_name = sys.argv[1] jenkins_port = sys.argv[2] JENKINS_SERVER_URL = 'http://' + jenkins_host_name + ':' + str(jenkins_port) JENKINS_SERVER_USER = os.getenv('JENKINS_USER', "admin") JENKINS_SERVER_PASS = os.getenv('JENKINS_PASS', "admin") try: server = jenkins.Jenkins(JENKINS_SERVER_URL, username=JENKINS_SERVER_USER, password=JENKINS_SERVER_PASS) print('Jenkins server: ' + JENKINS_SERVER_URL) result = server.get_version() print(result) except Exception as e: print("Error contacting jenkins") print(e) sys.exit(-1) sys.exit(0)
def connect_to_server(uri, username, password): server = jenkins.Jenkins(uri, username=username, password=password) return server
def __init__(self): try: self.server = jenkins.Jenkins("http://jenkins.dexter.com.br:8080/") except Exception as e: raise Exception(e)
#!/usr/bin/env python # _*_ coding: utf-8 _*_ # @Time : 6/19/2018 11:52 AM # @Author : Apy # @File : Python-Jenkins-version.py import sys import jenkins job_name = sys.argv[1] server = jenkins.Jenkins("http://jenkins.gmfcloud.com", username="******", password="******") user = server.get_whoami() version = server.get_version() print("Hello %s from Jenkins %s" % (user["fullName"], version)) job_info = server.get_job_info(job_name) print("%s" % job_info) build_job = server.build_job(job_name)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/1/9 14:42 # @Author : GXl # @File : jenkins # 定义远程的jenkins master server的url,用户名和密码 import jenkins jenkins_server_url = 'http://127.0.0.1:8080/' username = '******' password = '******' job_name = 'PyDemo' server = jenkins.Jenkins(jenkins_server_url, username=username, password=password) # 获取job名为job_name的信息 print("######", server.get_job_info(job_name)) # 获取job名为job_name的job的最后次构建号 build_number = server.get_job_info(job_name)['lastCompletedBuild']['number'] print(build_number) # 获取job名为job_name的job的某次构建的执行结果状态 print("######", server.get_build_info(job_name, build_number)['result']) #server.build_job(job_name) server.create_job("APIDemo", "")
import jenkins server = jenkins.Jenkins( 'http://localhost:8080', username='******', password='******') # place password here user = server.get_whoami() version = server.get_version() print('Hello %s from Jenkins %s' % (user['fullName'], version)) plugins = server.get_plugins_info() print plugins
def delete_job(self,job_name): if self.server.job_exists(job_name): self.server.delete_job(job_name) def rename_job(self,old_name,new_name): self.server.rename_job(old_name,new_name) if __name__ == '__main__': # jenkins_handler = JenkinsApi("http://10.12.208.89:8080", "admin", "e0f51bfdafb9bcccec1ab1e59aac0e41","a") # jenkins_handler.build_job({}) # server = jenkins.Jenkins("http://10.12.208.89:8080", username="******", password="******") # try: server = jenkins.Jenkins("http://10.12.12.157:8080", username="******", password="******") print(server.get_job_info('job4')) # print(server.get_version()) # server.jobs_count() # print(server.get_build_info('job4',12)['building']) # print(server.get_build_console_output('job4',12)) # print(server.build_job('job4',parameters={'group_list':'','operation':'','environment':''})) # ret = server.get_job_config('job22') # with open('ret1.xml','w') as f: # f.write(ret) svn_xml = ''' <scm class="hudson.scm.SubversionSCM" plugin="[email protected]"> <locations> <hudson.scm.SubversionSCM_-ModuleLocation> <remote>http://abc.com</remote> <credentialsId></credentialsId>
def startbuild(request): branch_name = request.POST.get("branch_name") tag_version = request.POST.get("tag_version") env = request.POST.get("env") appname = request.POST.get("appname") username = request.user.username job_name = get_jenkins_job_name(env, appname) print(branch_name, tag_version, env, appname, username, job_name) if env == "qa01" or env == "qa02": server = jenkins.Jenkins('http://jenkins.protest.xueba100.cc', username='******', password='******') if env == "qa02": job_name = "qa02-aixue-open-pro/" + job_name tag_version = "null" server.build_job(job_name, parameters={'branch_name': branch_name}) elif env == "plus": server = jenkins.Jenkins('http://jenkins.xueba100.cc', username='******', password='******') print(job_name, tag_version) server.build_job(job_name, parameters={ 'branch_name': branch_name, 'version': tag_version }) building_number = server.get_job_info(job_name)['builds'][0]['number'] building_number = building_number + 1 while True: try: status = server.get_build_info(job_name, building_number)['building'] result = server.get_build_info(job_name, building_number)['result'] except Exception as e: time.sleep(3) else: if status: time.sleep(3) else: if result == "SUCCESS": p = deploy_model.objects.create(appname=appname, deployer=username, env=env, tag_version=tag_version, build_status=1, branch_name=branch_name) print(p.id) message = "构建成功" else: p = deploy_model.objects.create(appname=appname, deployer=username, env=env, tag_version=tag_version, build_status=2, branch_name=branch_name) print(p.id) message = "构建失败 请检查分支名、tag号是否正确 或联系运维" break return JsonResponse({ "message": message, "result": result, "tag_version": tag_version, "deployer": username })
def __init__(self, url, username, password): self.server = jenkins.Jenkins(url=url, username=username, password=password)