Jenkins Multibranch Pipeline-以编程方式设置构建配置

时间:2019-06-12 13:10:44

标签: jenkins groovy jenkins-pipeline

我创建了一个脚本来使用Groovy文件中的Multibranch Pipeline自动初始化Jenkins实例

/* Adds a multibranch pipeline job to Jenkins */
import hudson.model.*
import hudson.plugins.git.extensions.impl.UserIdentity
import hudson.util.PersistedList
import jenkins.*
import jenkins.branch.*
import jenkins.model.*
import jenkins.model.Jenkins
import jenkins.plugins.git.*
import jenkins.plugins.git.traits.*
import jenkins.scm.impl.trait.RegexSCMHeadFilterTrait
import com.cloudbees.hudson.plugins.folder.computed.PeriodicFolderTrigger
import org.jenkinsci.plugins.workflow.multibranch.*
// Create job
def env = System.getenv()
Jenkins jenkins = Jenkins.instance
String jobName = "Flow"
String jobScript = "flow/cicd/Jenkinsfile"
def job = jenkins.getItem(jobName)
// Create the folder if it doesn't exist
if (job == null) {
  job = jenkins.createProject(WorkflowMultiBranchProject.class, jobName)
}
job.getProjectFactory().setScriptPath(jobScript)
// Add git repository
String remote = env.CODE_COMMIT_URL
GitSCMSource gitSCMSource = new GitSCMSource(remote)
BranchSource branchSource = new BranchSource(gitSCMSource)
// Remove and replace?
PersistedList sources = job.getSourcesList()
sources.clear()
sources.add(branchSource)
// Add traits
String username = "Jenkins"
String email = "jenkins@email.com"
String regexExclude = "^(?!no-cicd).*"
def traits = []
traits.add(new BranchDiscoveryTrait())
traits.add(new LocalBranchTrait())
traits.add(new TagDiscoveryTrait())
traits.add(new UserIdentityTrait(new UserIdentity(username, email)))
traits.add(new RegexSCMHeadFilterTrait(regexExclude))
gitSCMSource.setTraits(traits)
// Periodic trigger
job.addTrigger(new PeriodicFolderTrigger("1m"))

我想知道是否有办法从构建配置中删除Jenkinsfile并以编程方式添加它,也使用Groovy文件吗?例如,我不是在Groovy文件中使用String jobScript = "flow/cicd/Jenkinsfile",而是使用

String buildConfiguration = "
pipeline {
  agent any
  tools {
    nodejs "nodejs"
  }
  environment { 
    CI = 'true'
  } 
  stages {
    stage("Checkout") {
      steps {
        checkout scm
        sh "git fetch --tags"
      }
    }
...

目前,我唯一的选择是设置一个Jenkinsfile,如下所示。

enter image description here

0 个答案:

没有答案