如何使用groovy创建和配置新的Jenkins作业?

时间:2013-06-06 13:23:25

标签: groovy jenkins

有很多groovy脚本的例子(http://scriptlerweb.appspot.com/catalog/list)但是我没有找到新的创造就业机会的例子。网上有一个很好的例子,说明应该如何做到这一点吗?

4 个答案:

答案 0 :(得分:7)

从SCM创建管道脚本作业:

import hudson.plugins.git.*;

def scm = new GitSCM("git@github.com:dermeister0/Tests.git")
scm.branches = [new BranchSpec("*/develop")];

def flowDefinition = new org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition(scm, "Jenkinsfile")

def parent = Jenkins.instance
def job = new org.jenkinsci.plugins.workflow.job.WorkflowJob(parent, "New Job")
job.definition = flowDefinition

parent.reload()

另一个例子:https://github.com/linagora/james-jenkins/blob/master/create-dsl-job.groovy

答案 1 :(得分:3)

Jenkins插件Job DSL Plugin可以在作业中添加步骤来创建/修改现有作业。

这是插件网站上的示例,它为git存储库中的每个分支创建一个作业:

def project = 'quidryan/aws-sdk-test'
def branchApi = new URL("https://api.github.com/repos/${project}/branches")
def branches = new groovy.json.JsonSlurper().parse(branchApi.newReader())
branches.each {
    def branchName = it.name
    def jobName = "${project}-${branchName}".replaceAll('/','-')
    job(jobName) {
        scm {
            git("git://github.com/${project}.git", branchName)
        }
        steps {
            maven("test -Dproject.name=${project}/${branchName}")
        }
    }
}

答案 2 :(得分:3)

鉴于您有一个包含新作业的config.xml的XML字符串,以下groovy脚本将执行您想要的操作。

import jenkins.model.*

def jobName = "my-new-job"
def configXml = "" // your xml goes here

def xmlStream = new ByteArrayInputStream( configXml.getBytes() )

Jenkins.instance.createProjectFromXML(jobName, xmlStream)

有关详细信息,请参阅API Docs

答案 3 :(得分:0)

def jobDSL="""
node {
  stage("test"){
   echo 'Hello World'
  }
}

""";
//http://javadoc.jenkins.io/plugin/workflow-cps/index.html?org/jenkinsci/plugins/workflow/cps/CpsFlowDefinition.html
def flowDefinition = new org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition(jobDSL, true);
//http://javadoc.jenkins.io/jenkins/model/Jenkins.html
def parent = Jenkins.instance;
//parent=Jenkins.instance.getItemByFullName("parentFolder/subFolder")
//http://javadoc.jenkins.io/plugin/workflow-job/org/jenkinsci/plugins/workflow/job/WorkflowJob.html
def job = new org.jenkinsci.plugins.workflow.job.WorkflowJob(parent, "testJob")
job.definition = flowDefinition

job.setConcurrentBuild(false);

//http://javadoc.jenkins.io/plugin/branch-api/jenkins/branch/RateLimitBranchProperty.html
job.addProperty( new jenkins.branch.RateLimitBranchProperty.JobPropertyImpl
    (new jenkins.branch.RateLimitBranchProperty.Throttle (60,"hours")));
def spec = "H 0 1 * *";
hudson.triggers.TimerTrigger newCron = new hudson.triggers.TimerTrigger(spec);
newCron.start(job, true);
job.addTrigger(newCron);
job.save();


Jenkins.instance.reload()