Arne
Arne

Reputation: 2674

Jenkins Job DSL: How to read Pipeline DSL script from file?

I want to generate my pipeline plugin based jobs via Job DSL, which is contained in a git repository that is checked out by Jenkins.

However, I think it is not very nice to have the pipeline scripts as quoted Strings inside of the Job DSL script. So I want to read them into a string and pass that to the script() function:

definition {
   cps {
      sandbox()
         script( new File('Pipeline.groovy').text )
      }
   }
}

Where do I have to put Pipeline.groovy for this to work? I tried putting it right next to my DSL script, and also in the resources/ folder of my DSL sources. But Jenkins always throws a "file not found".

Upvotes: 2

Views: 3957

Answers (2)

J.Z.
J.Z.

Reputation: 941

Ref the Job DSL pipelineJob: https://jenkinsci.github.io/job-dsl-plugin/#path/pipelineJob, and hack away at it on http://job-dsl.herokuapp.com/ to see the generated config.

The Job DSL below creates a pipeline job, which pulls the actual job from a Jenkinsfile:

pipelineJob('DSL_Pipeline') {

  def repo = 'https://github.com/path/to/your/repo.git'

  triggers {
    scm('H/5 * * * *')
  }
  description("Pipeline for $repo")

  definition {
    cpsScm {
      scm {
        git {
          remote { url(repo) }
          branches('master', '**/feature*')
          scriptPath('misc/Jenkinsfile.v2')
          extensions { }  // required as otherwise it may try to tag the repo, which you may not want
        }

        // the single line below also works, but it
        // only covers the 'master' branch and may not give you
        // enough control.
        // git(repo, 'master', { node -> node / 'extensions' << '' } )
      }
    }
  }
}

You/your Jenkins admins may want to separate Jenkins job creation from the actual job definition. That seems sensible to me ... it's not a bad idea to centralize the scripts to create the Jenkins jobs in a single Jenkins DSL repo.

Upvotes: 1

user2404015
user2404015

Reputation: 11

have you tried readFileFromWorkspace()? it should be able find the files you checkout from git.

Upvotes: 1

Related Questions