jenkinsjenkins-pluginsjenkins-job-dsljcasc

How to create a jenkins pipelineJob via Configuration as code?


I want to create a simple pipeline job in my Jenkins configuration with a script. So my jenkins.yaml file is as follow:

 jobs:
  - script: >
      pipelineJob('Tag Repositories') {
        definition {
          cps {
            def theScript = readFileFromWorkspace('git_tag_job.groovy')
            script(theScript)
            sandbox()
          }
        }
      }

So I thought the file git_tag_job.groovy can be in Jenkins home directory but it looks like that readFileFromWorkspace is looking at the workspace of this job which hasn't been created yet. As the result, I get NPE error because workspace is null.

Now the question is how can I use Configuration As Code plugin to add this job with the content of the git_tag_job.groovy as its script?

The script is huge and I can't put it in the Yaml file.

What wonders me is that, this configuration and readFileFromWorkspace is useless if we can't load the script from somewhere because it's very rare that you have a pipeline job with one-line script so loading from a file is the only practical option.

Have I missed anything here or is there any other way to do this?


Solution

  • I know this is an old question but I faced the exact same problem, so here's a solution following @xbmono's comment for anyone who stumble here:

    I chose to separate the seed job dsl script from the yaml file but it's basically the same.

    casc.yaml

    ...
    jobs:
      -file: /abs/path/to/seedjob.groovy
    

    seedjob.groovy

    theScript = new File('/abs/path/to/git_tag_job.groovy').getText("UTF-8")
    pipelineJob('Tag Repositories') {
      definition {
        cps {
          script(theScript)
          sandbox()
        }
      }
    }