本文整理汇总了Python中jenkins.Jenkins.create_job方法的典型用法代码示例。如果您正苦于以下问题:Python Jenkins.create_job方法的具体用法?Python Jenkins.create_job怎么用?Python Jenkins.create_job使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类jenkins.Jenkins
的用法示例。
在下文中一共展示了Jenkins.create_job方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import create_job [as 别名]
def main(argv):
parser = OptionParser(version=VERSION)
parser.add_option("-c", "--create-job", dest="create_job",
help="Task to create a new job",
action="store_true")
parser.add_option("-j", "--job-name", dest="job_name",
help="Job's name",
metavar="CREATE")
parser.add_option("-f", "--file", dest="filename",
help="Path do jenkins config file",
metavar="FILE")
parser.add_option("-u", "--url", dest="url",
help="Jenkins server URL",
metavar="FILE")
options, _ = parser.parse_args()
validate(options)
ci = Jenkins(url=options.url)
config = ""
with open(options.filename, "r") as config_file:
config = config_file.read()
config_file.close()
job_name = options.job_name
if options.create_job:
ci.create_job(job_name, config)
示例2: __init__
# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import create_job [as 别名]
class JobBuilder:
def __init__(self, jenkinsURL):
self.j = Jenkins(jenkinsURL)
self.jobName = ""
def add_job(self, jobName, configString):
self.jobName = jobName
if self.j.job_exists(jobName):
#Job exist in the job list
return False
else:
self.j.create_job(self.jobName, configString)
self.j.enable_job(self.jobName)
return True
def run_job(self, **params):
if self.jobName == "":
print "Have to add job firstly"
return False
else:
self.j.enable_job(self.jobName)
self.j.build_job(self.jobName, params)
示例3: config_jenkins
# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import create_job [as 别名]
def config_jenkins(self, jenkins_url, jenkins_config_file, job_name):
ci = Jenkins(url=jenkins_url)
config = ""
with open(jenkins_config_file, "r") as config_file:
config = config_file.read()
config_file.close()
ci.create_job(job_name, config)
示例4: reportUsingJenkinsEmailPlugin
# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import create_job [as 别名]
def reportUsingJenkinsEmailPlugin(self, marvinConfigJson, env, execOnOneZone = True):
try:
jobIdentifierList = []
bugLoggerData = []
j = Jenkins('http://jenkins-ccp.citrix.com', 'bharatk', 'BharatK')
for zone in cscfg.zones:
self.logger.info(zone.name)
for pod in zone.pods:
for cluster in pod.clusters:
self.logger.info('creating a jeknins job to generate results and email notfication for hypervisor %s and zone %s' % (cluster.hypervisor, zone.name))
modifiedjob = jobModifier.modifyReportGenerator(env['build_number'] + '_' + zone.name + '_' + cluster.hypervisor, mailto)
jobname = modifiedjob
file = open('/root/cloud-autodeploy2/newcode/' + modifiedjob, 'r')
config = file.read()
file.close()
j.create_job(modifiedjob, config)
j.build_job(modifiedjob, {'buildNumber': env['build_number'],
'BuildNo': env['build_number'],
'MGMT_SVR': env['hostip'],
'BASEDIR': env['virtenvPath'],
'version': env['version'],
'BranchInfo': env['version'],
'GitRepoUrl': env['repo_url'],
'GitCommitId': env['commit_id'],
'CIRunStartDateTime': env['startTime'],
'CIRunEndDateTime': time.strftime('%c'),
'WikiLinks': 'https://cwiki.apache.org/confluence/display/CLOUDSTACK/Infrastructure%2CCI%2CSimulator%2CAutomation+Changes',
'hypervisor': cluster.hypervisor.lower(),
'HyperVisorInfo': cluster.hypervisor.lower(),
'zoneName': zone.name,
'BuildReport': 'https://www.dropbox.com/sh/yj3wnzbceo9uef2/AAB6u-Iap-xztdm6jHX9SjPja?dl=0',
'token': 'bharat'})
jobIdentifierList.append('report_' + zone.name)
jobDetails = {'job_name': modifiedjob,
'related_data_path': env['virtenvPath']}
self.resourceMgr.addJobDetails(jobDetails)
bugLoggerData.append({'hypervisor': cluster.hypervisor.lower(),
'branch': env['version'],
'logname': cluster.hypervisor.lower() + '__Log_' + env['build_number'],
'type': 'BVT'})
self.logger.info('bug logger data in zone looop %s' % bugLoggerData)
self.waitForJobComplete(env['virtenvPath'], jobIdentifierList)
self.archiveTestRunLogs(env, cluster.hypervisor.lower(), jobname)
break
break
if execOnOneZone:
break
self.logger.info('job identifier list %s' % jobIdentifierList)
self.logger.info('cleaning up the workspace')
bash('rm -f /root/cloud-autodeploy2/newcode/%s' % modifiedjob)
self.logger.info('running bug logger')
except Exception as e:
self.logger.exception(e)
示例5: create_jenkins_job
# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import create_job [as 别名]
def create_jenkins_job(init_job_config, job_name):
"""
Create new job by getting config file
from existing job
"""
j = Jenkins("http://localhost:8080")
str_config = j.get_job_config(init_job_config)
if j.job_exists(job_name) == False:
j.create_job(job_name, str_config)
示例6: configure
# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import create_job [as 别名]
def configure(self):
#self.logger.info("setting jenkins authentication method to use unix userdata")
#self.checkForSuccess(bash("cp %s/jenkis_auth_file /var/lib/jenkins"%currentDir))
#self.logger.info("setting jenkins password")
#self.logger.info("echo %s | sudo passwd jenkins --stdin"%self.jenkinsPasswd)
#self.checkForSuccess(bash("service jenkins restart"))
time.sleep(10)
self.logger.info("checking if auth config is successful")
j=Jenkins(self.jenkinsUrl, "admin", self.jenkinsPasswd)
try:
j.get_plugins()
except Exception as e:
self.logger.info("failed to retrive plugin info, may be auth problem")
self.logger.exception(e)
raise e
self.logger.info("auth config successful")
self.logger.info("installing requried plugins")
self.logger.info("reading from jenkins plugins file %s/jenkins_plugins.txt"%currentDir)
f=open('%s/jenkins_plugins.txt'%currentDir, 'r')
pluginsToInstall=f.read()
pluginsToInstall=pluginsToInstall.split('\n')
self.installPlugins(j,pluginsToInstall)
self.logger.info("Plugin installation complete")
self.logger.info("restarting jenkins")
self.restartJenkins()
self.logger.info("Creating CI jobs on jenkins")
for file in os.listdir(os.path.join(currentDir,'jenkins_job_templates')):
try:
if not j.job_exists(file):
f=open(os.path.join(currentDir,'jenkins_job_templates',file),'r')
config=f.read()
f.close()
self.logger.info("creating job %s, reading config from file %s"%(repr(file),os.path.join(currentDir,'jenkins_job_templates',file)))
j.create_job(file, config)
else:
self.logger.info("job %s already exists, not creating"%file)
except Exception as e:
self.logger.warn("failed to create job %s"%(file))
self.logger.exception(e)
self.logger.info("created all CI jobs")
self.logger.info("Adding driverVM as node in jenkins")
params = {
'port': '22',
'username': 'jenkins',
'credentialsId':'abe3f139-77bd-4db4-824b-1c79d5205d8b',
'host':self.config['nodes']['driverVM']['ip']
}
self.addPasswdToCredential(j,"vagrant")
self.checkForSuccess(bash("cp %s /var/lib/jenkins/."%(os.path.join(currentDir,"jenkins_credentials","credentials.xml"))))
j.create_node('driverVM', numExecutors=20, nodeDescription="CI slave VM", remoteFS='/automation/jenkins', labels='driverVM', exclusive=True,launcher=jenkins.LAUNCHER_SSH, launcher_params=params)
self.logger.info("jenkins install complete")
示例7: run
# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import create_job [as 别名]
def run(self):
# Run the egg_info step to find our VCS url.
self.run_command('egg_info')
if not self.distribution.metadata.url:
log.warn("This package does not appear to be in any repository, "
"aborting.")
sys.exit(1)
# Pull down Jenkins package
base.fetch_build_eggs(['python-jenkins'], dist=self.distribution)
from jenkins import Jenkins
server = CONFIG.jenkins_url
log.info("Connecting to Jenkins at %s" % server)
jenkins = Jenkins(server, self.username, self.password)
name = self.distribution.metadata.name
if (self.matrix):
log.info("Matrix job")
if CONFIG.jenkins_matrix_job_xml:
path, fname = CONFIG.jenkins_matrix_job.split(':')
else:
path, fname = None, 'jenkins_job_matrix.xml'
else:
log.info("Non-matrix job - use \'--matrix\' option for matrix builds")
if CONFIG.jenkins_job_xml:
path, fname = CONFIG.jenkins_job.split(':')
else:
path, fname = None, 'jenkins_job.xml'
with open(base.get_resource_file(fname, path)) as f:
jenkins_config_xml = Template(f.read())
cfg_xml = jenkins_config_xml.safe_substitute(
name=cgi.escape(name),
hyphen_escaped_name=cgi.escape(name).replace("-", "?").replace("_", "?"),
description=cgi.escape(self.distribution.metadata.description),
repository=self.distribution.metadata.url,
email=self.distribution.metadata.author_email,
python_string_xml=self._construct_string_values(self._get_active_python_versions()),
virtualenv=CONFIG.virtualenv_executable,
username=self.username
)
if jenkins.job_exists(name):
log.error("Job found at %s/job/%s Please delete this before creating a new one." % (server, name))
else:
if (not self.dry_run):
log.info("Creating job at %s/job/%s" % (server, name))
jenkins.create_job(name, cfg_xml)
示例8: run
# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import create_job [as 别名]
def run(self):
# Run the egg_info step to find our VCS url.
self.run_command('egg_info')
if not self.distribution.metadata.url:
print "This package does not appear to be in any repository, aborting."
sys.exit(1)
# Pull down jenkins package
self.fetch_build_eggs(['python_jenkins'])
from jenkins import Jenkins
print "Connecting to Jenkins at %s" % self.server
# Prompt for password or use command-line
if self.no_prompt:
if self.password is None:
print "Must specify password if no-prompt is set."
sys.exit(1)
password = self.password
else:
password = getpass.getpass("Please enter your Jenkins password: ")
jenkins = Jenkins(self.server, self.username, password)
name = self.distribution.metadata.name
cfg_xml = JENKINS_CFG_XML.safe_substitute(
name=name,
description=self.distribution.metadata.description,
repository=self.distribution.metadata.url,
email=self.distribution.metadata.author_email,
virtualenv=CONFIG.virtualenv_executable,
)
if jenkins.job_exists(name):
if not self.no_prompt:
while True:
user_input = raw_input("Job already exists, update configuration? [y/n]")
if not user_input in ('y', 'n'):
continue
break
if user_input == 'n':
return
print "Reconfiguring job at %s/job/%s" % (self.server, name)
jenkins.reconfig_job(name, cfg_xml)
else:
print "Creating job at %s/job/%s" % (self.server, name)
jenkins.create_job(name, cfg_xml)
示例9: __init__
# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import create_job [as 别名]
class TaskBuilder:
def __init__(self, jenkinsURL):
self.j = Jenkins(jenkinsURL)
self.jobName = ""
with open("config.xml") as file:
self.templateConfig = file.read()
self.template = Template(unicode(self.templateConfig))
def set_new_config(self, **params):
self.newConfig = self.template.render(repos=params['repos'], description=params['repos'])
def add_build(self, **params):
self.set_job_name(**params)
self.set_new_config(**params)
if self.j.job_exists(self.jobName):
self.do_build(**params)
else:
self.j.create_job(self.jobName, self.newConfig)
self.do_build(**params)
def do_build(self, **params):
self.set_job_name(**params)
self.set_new_config(**params)
self.j.enable_job(self.jobName)
self.j.build_job(self.jobName, {'branch': params['branch'], 'version': params['version'], 'package_list': params['package_list']})
def set_job_name(self,**params):
buildUtil = BuildUtil()
self.jobName = buildUtil.get_job_name(repos=params['repos'])
def get_build_status(self, **params):
#job_info = self.j.get_job_info(self.jobName)
#return build_status
pass
def get_job_name(self):
return self.jobName
示例10: JenkinsControl
# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import create_job [as 别名]
class JenkinsControl(object):
war=pjoin(here, 'tmp/jenkins.war')
cli=pjoin(here, 'tmp/jenkins-cli.jar')
home=pjoin(here, 'tmp/jenkins')
def __init__(self, addr='127.0.0.1:60888', cport='60887'):
self.addr, self.port = addr.split(':')
self.url = 'http://%s' % addr
self.py = Jenkins(self.url)
def start_server(self):
cmd = pjoin(here, './bin/start-jenkins.sh 1>/dev/null 2>&1')
env={'JENKINS_HOME' : self.home,
'JENKINS_PORT' : self.port,
'JENKINS_CPORT' : self.cport,
'JENKINS_ADDR' : self.addr}
check_call(cmd, shell=True, env=env)
def shutdown_server(self):
cmd = 'echo 0 | nc %s %s' % (self.addr, self.cport)
check_call(cmd, shell=True)
def clean_home(self):
rmtree(self.home)
def createjob(self, name, configxml_fn):
self.py.create_job(name, open(configxml_fn).read())
def getjobs(self):
return {i['name'] : i for i in self.py.get_jobs()}
def enabled(self, name):
return self.py.get_job_info(name)['buildable']
def job_etree(self, job):
res = self.py.get_job_config(job)
res = etree.fromstring(res)
return res
示例11: JenkinsBot
# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import create_job [as 别名]
#.........这里部分代码省略.........
"""
self.connect_to_jenkins()
try:
queue = self.jenkins.get_queue_info()
job = next((job for job in queue if job['task']['name'].lower() == args.lower()), None)
if job:
self.jenkins.cancel_queue(job['id'])
return 'Unqueued job {0}'.format(job['task']['name'])
else:
return 'Could not find job {0}, but found the following: {1}'.format(
args, ', '.join(job['task']['name'] for job in queue))
except JenkinsException as e:
return 'Oops, {0}'.format(e)
@botcmd(split_args_with=None)
def jenkins_createjob(self, mess, args):
"""Create a Jenkins Job.
Example: !jenkins createjob pipeline foo [email protected]:foo/bar.git
"""
if len(args) < 2: # No Job type or name
return 'Oops, I need a type and a name for your new job.'
if args[0] not in ('pipeline', 'multibranch'):
return 'I\'m sorry, I can only create `pipeline` and \
`multibranch` jobs.'
self.connect_to_jenkins()
try:
if args[0] == 'pipeline':
self.jenkins.create_job(
args[1],
JENKINS_JOB_TEMPLATE_PIPELINE.format(repository=args[2]))
elif args[0] == 'multibranch':
repository = args[2].rsplit('/', maxsplit=2)[-2:]
self.jenkins.create_job(
args[1],
JENKINS_JOB_TEMPLATE_MULTIBRANCH.format(
repo_owner=repository[0].split(':')[-1],
repo_name=repository[1].strip('.git')))
except JenkinsException as e:
return 'Oops, {0}'.format(e)
return 'Your job has been created: {0}/job/{1}'.format(
self.config['URL'], args[1])
@botcmd(split_args_with=None)
def jenkins_deletejob(self, mess, args):
"""Delete a Jenkins Job.
Example: !jenkins deletejob foo
"""
if len(args) < 1: # No job name
return 'Oops, I need the name of the job you want me to delete.'
self.connect_to_jenkins()
try:
self.jenkins.delete_job(args[0])
except JenkinsException as e:
return 'Oops, {0}'.format(e)
return 'Your job has been deleted.'
示例12: execOnJenkins
# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import create_job [as 别名]
def execOnJenkins(self, env, testSpecifierString, mailto, reRunFailedTests=True, retryCount=1, report=True, execOnOneZone=True,
postOnPr=False, testMgr=None, avoidZones=None):
try:
env['hypervisor'] = ''
if avoidZones is None:
avoidZones=[]
if testMgr is None:
testMgr = testManager(testSpecifierString, env['virtenvPath'])
jobModifier = modifyJOb()
modifiedjob = ''
j = Jenkins('http://jenkins-ccp.citrix.com', 'bharatk', 'BharatK')
tests = testMgr.getTests()
if tests == None:
raise Exception('found no tests to run')
while tests is not None:
os.chdir(env['virtenvPath'])
self.logger.info('launching jenkins TestExecutor Job')
cscfg = configGenerator.getSetupConfig(env['config_file'])
for zone in cscfg.zones:
if zone.name in avoidZones:
continue
for pod in zone.pods:
for cluster in pod.clusters:
for modifiedjob in jobModifier.addTests(env['build_number'], tests, self.throttle_job_count):
file = open('/root/cloud-autodeploy2/newcode/' + modifiedjob, 'r')
config = file.read()
file.close()
bash('rm -f /root/cloud-autodeploy2/newcode/%s' % modifiedjob)
if not j.job_exists(modifiedjob):
j.create_job(modifiedjob, config)
else:
j.delete_job(modifiedjob)
j.create_job(modifiedjob, config)
j.build_job(modifiedjob, {'BASEDIR': env['virtenvPath'],
'MGMT_SVR': env['hostip'],
'buildNumber': env['build_number'],
'zoneName': zone.name,
'hypervisor': cluster.hypervisor.lower(),
'zoneType': zone.networktype,
'configFileName': env['config_file'],
'token': 'bharat'})
self.waitForJobComplete(env['virtenvPath'], [zone.name])
env['hypervisor'] = '%s,%s' % (env['hypervisor'], cluster.hypervisor.lower())
break
break
if execOnOneZone:
break
tests = testMgr.getTests()
j.delete_job(modifiedjob)
reportAnalyserMap=self.getReportAnalysers(cscfg, env, execOnOneZone)
if(reRunFailedTests):
while retryCount > 0:
self.logger.info("checking if we need to re run any of the tests")
testsToReRun=[]
for key in reportAnalyserMap.keys():
tests=reportAnalyserMap[key].suitsToRerun
if(tests is None):
avoidZones.append(key)
else:
testMgr.addTestsToReRun(tests)
retryCount-=1
self.logger.info("zone name:%s The follwoing tests will be re run %s"%(key,tests))
if(len(testsToReRun)==0):
break
else:
self.execOnJenkins(env, testSpecifierString, mailto, reRunFailedTests, retryCount, False, execOnOneZone, postOnPr, testMgr, avoidZones)
if report and postOnPr:
for key in reportAnalyserMap.keys():
self.reportOnPr(reportAnalyserMap[key].generateTextReport2(), env)
elif report:
self.reportUsingJenkinsEmailPlugin(cscfg, env)
return env
except Exception as e:
self.logger.exception(e)
示例13: execOnJenkins
# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import create_job [as 别名]
def execOnJenkins(self,env,testSpecifierString,mailto,execOnOneZone=True):
try:
testMgr=testManager(testSpecifierString,env['virtenvPath'])
jobModifier=modifyJOb()
modifiedjob=""
j=Jenkins('http://jenkins-ccp.citrix.com','bharatk','BharatK')
tests=testMgr.getTests()
if(tests==None):
raise Exception("found no tests to run")
while(not tests is None):
#trigger a jenkins job.
os.chdir(env['virtenvPath'])
self.logger.info("launching jenkins TestExecutor Job")
#createing testexecutorjobs for each zone.
cscfg=configGenerator.getSetupConfig(env['config_file'])
jobIdentifierList=[]
for zone in cscfg.zones:
for pod in zone.pods:
for cluster in pod.clusters:
modifiedjob=jobModifier.addTests(env['build_number'],tests)
file=open("/root/cloud-autodeploy2/newcode/"+modifiedjob,'r')
config=file.read()
file.close()
bash("rm -f /root/cloud-autodeploy2/newcode/%s"%modifiedjob)
if(not j.job_exists(modifiedjob)):
j.create_job(modifiedjob,config)
else:
j.reconfig_job(modifiedjob,config)
j.build_job(modifiedjob, {'BASEDIR':env['virtenvPath'], 'MGMT_SVR' : env['hostip'],'buildNumber':env['build_number'],'zoneName':zone.name,'hypervisor':cluster.hypervisor.lower(),'zoneType':zone.networktype,'configFileName':env['config_file'],'token':'bharat'})
jobIdentifierList.append(zone.name)
break
break
if (execOnOneZone):
break
self.waitForJobComplete(env['virtenvPath'],jobIdentifierList)
tests=testMgr.getTests()
j.delete_job(modifiedjob)
jobIdentifierList=[]
bugLoggerData=[]
time.sleep(30)
for zone in cscfg.zones:
self.logger.info(zone.name)
for pod in zone.pods:
for cluster in pod.clusters:
self.logger.info("creating a jeknins job to generate results and email notfication for hypervisor %s and zone %s"%(cluster.hypervisor, zone.name))
modifiedjob=jobModifier.modifyReportGenerator(env['build_number']+"_"+zone.name+"_"+cluster.hypervisor, mailto)
jobname=modifiedjob
file=open("/root/cloud-autodeploy2/newcode/"+modifiedjob,'r')
config=file.read()
file.close()
j.create_job(modifiedjob,config)
j.build_job(modifiedjob, {'buildNumber':env['build_number'],'BuildNo':env['build_number'], 'MGMT_SVR' : env['hostip'], 'BASEDIR':env['virtenvPath'], 'version':env['version'], 'BranchInfo':env['version'],\
'GitRepoUrl':env['repo_url'],'GitCommitId':env['commit_id'], 'CIRunStartDateTime':env['startTime'],'CIRunEndDateTime':time.strftime("%c"), 'WikiLinks':'https://cwiki.apache.org/confluence/display/CLOUDSTACK/Infrastructure%2CCI%2CSimulator%2CAutomation+Changes','hypervisor':cluster.hypervisor.lower(), 'HyperVisorInfo':cluster.hypervisor.lower(), 'zoneName':zone.name, 'BuildReport':"http://jenkins-ccp.citrix.com/job/"+jobname+"/1/testReport/",'token':'bharat'})
jobIdentifierList.append("report_"+zone.name)
jobDetails={"job_name":modifiedjob,"related_data_path":env['virtenvPath']}
self.resourceMgr.addJobDetails(jobDetails)
bugLoggerData.append({'hypervisor':cluster.hypervisor.lower(), 'branch':env['version'],'logname':cluster.hypervisor.lower()+'__Log_'+env['build_number'], 'type':'BVT'})
self.logger.info("bug logger data in zone looop %s"%bugLoggerData)
break
break
if (execOnOneZone):
#env['hypervisor':cluster.hypervisor.lower()]
break
self.logger.info("job identifier list", jobIdentifierList)
self.waitForJobComplete(env['virtenvPath'],jobIdentifierList)
#self.logger.info("deleting the reporter job on jenkins job_name=%s",jobname)
#j.delete_job(jobname)
self.logger.info("cleaning up the workspace")
bash("rm -f /root/cloud-autodeploy2/newcode/%s"%modifiedjob)
self.logger.info("running bug logger")
#self.runBugLogger(bugLoggerData)
#os.system("rm -rf %s"%(self.jenkinsWorkspace+"/"+jobname))
except Exception, e:
self.logger.error(e)