title: Jenkins Multibranch Pipeline - setup build configuration programmatically
body: <p>I've created a script to initialize my Jenkins instance automatically using Multibranch Pipeline in a Groovy file</p>
  
  <pre><code>/* 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"))
  </code></pre>
  
  <p>I'd like to know if there is a way to remove Jenkinsfile from the build configuration and add it programmatically, using Groovy files too? For instance, instead of having <code>String jobScript = "flow/cicd/Jenkinsfile"</code> in Groovy file, I'd have</p>
  
  <pre><code>String buildConfiguration = "
  pipeline {
    agent any
    tools {
      nodejs "nodejs"
    }
    environment { 
      CI = 'true'
    } 
    stages {
      stage("Checkout") {
        steps {
          checkout scm
          sh "git fetch --tags"
        }
      }
  ...
  </code></pre>
  
  <p>Currently, the only option I have is setting up a Jenkinsfile as shown below.</p>
  
  <p><a href="https://i.stack.imgur.com/kqPQe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kqPQe.png" alt="enter image description here"></a></p>