jenkins-job-dsljcasc

Pass Variable on a Per-File Basis in Jenkins Configuration as Code Job DSL


https://github.com/jenkinsci/job-dsl-plugin/wiki/JCasC provides the following example of a separate groovy file referenced in the Jenkins Configuration as Code (CasC) syntax.

jobs:
  - providedEnv:
      SUPERHERO: 'Midnighter'
  - file: ./jobdsl/job.groovy
//job.groovy
job('awesome-job') {
    description("favorite job of ${SUPERHERO}")
}

I'm looking for a way of defining a few very similar jobs which only differ by a value or two. In the example above, the SUPERHERO variable looks to be a global, but I need a way to reuse the same groovy include with per-include variables.

Pseudo-code example:

jobs:
 - file: ./jobdsl/job.groovy
   providedEnv:
      SUPERHERO: 'Superman'
 - file: ./jobdsl/job.groovy
   providedEnv:
      SUPERHERO: 'Batman'

Does such a construct exist?


Solution

  • This appears to work:

    jobs:
      - providedEnv:
          SUPERHERO: 'Batman' 
      - file: ./jobdsl/job.groovy
      - providedEnv:
          SUPERHERO: 'Superman' 
      - file: ./jobdsl/job.groovy
    

    But I don't know if I'm exploiting a fragile, undocumented behavior or not.

    I would prefer to see an explicit association of the environment variables with the file reference; something like this:

    jobs:
     - file: ./jobdsl/job.groovy
       providedEnv:
          SUPERHERO: 'Batman'
     - file: ./jobdsl/job.groovy
       providedEnv:
          SUPERHERO: 'Superman'
    

    ...but alas this (guess at a) syntax doesn't work. (Jenkins starts but the jobs are absent.)