2

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?

P Ekambaram
  • 15,499
  • 7
  • 34
  • 59
xbmono
  • 2,084
  • 2
  • 30
  • 50

2 Answers2

2

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()
    }
  }
}

LonelyDaoist
  • 665
  • 8
  • 22
0

seed job creation by CasC run without a workspace, by design. Your whole configuration should be managed "as code" and versioned. in you case the job script could be loaded from an URL, git tag, etc.

nicolas de loof
  • 2,593
  • 1
  • 13
  • 11
  • 4
    yes but this case is slightly different. The job itself is part of the configuration for our jenkins stored in source control. The reason we have them in source code is to be able to tear down the whole jenkins env and start it up without loosing all its configurations. Anyway I ended up using groovy `new File(pathToFile).text` and it works now – xbmono Feb 03 '19 at 22:56