How create and configure a new Jenkins Job using groovy?

Pav*_*tam 11 groovy jenkins

There are a lot of examples of groovy scripts (http://scriptlerweb.appspot.com/catalog/list) no no example of new job creation.

Der*_*ter 8

从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()
Run Code Online (Sandbox Code Playgroud)

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


Kee*_*yOn 6

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}")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)