mrooney
mrooney

Reputation: 2022

Is it possible to override a Job DSL parameter?

We're using the Jenkins Job DSL plugin to configure all our jobs in code, and often use a local Jenkins staging environment to test in before deploying changes. We don't want our whole slew of hundreds of jobs to start building locally, though we do want to make sure the DSL is valid and the jobs are all created correctly.

Is there a way to override for example the scm parameter of a trigger so that it is a no-op locally, across all of our groovy files? I believe I could write a custom library file that does this, but then I'd have to add an import line to every groovy file to import our custom scm definition, which isn't ideal.

To clarify, I'm looking for a way to override certain definitions, elegantly or by monkey patching code, so that we don't have to require a change to every groovy file and job definition, of which there are a lot.

Upvotes: 0

Views: 1847

Answers (3)

crasp
crasp

Reputation: 743

If you want to make sure the DSL is valid, write some unit tests. You can see some examples here or here. Especially this test will tell you, if everything can be generated without any issues. If you want to generate them locally anyway to test if the build itself completes, you can use a system groovy script after your SeedJob generated all the configurations, to disable all automatic triggers. Here is an example on how to do that.

Upvotes: 0

tarantoga
tarantoga

Reputation: 1106

What works for me is:

  1. Add a function that returns true/false depending whether it's running in a production or test environment, based on current host name. E.g. I have production instance running as jenkins.mydomain.com, and test jenkins as jenkins-test.mydomain.com.
  2. Add a if/then/else in the job's definition based on that

e.g. like this:

Put this into JenkinsInstance.groovy:

import jenkins.model.*

// Representing the Jenkins server instance
class JenkinsInstance {
    // Determine if we're executing on a Jenkins production instance.
    static Boolean isProd() {
        if (Jenkins.getInstance().getRootUrl() ==~ ".*jenkins\\.mydomain\\..*") {
          return true
        } else {
          return false
        }
    }
}

The have your job creation DSL scripts look like this

import JenkinsInstance

freeStyleJob("myjobname") {
  if (JenkinsInstance.isProd()) {
    scm {
       git {
       ...
       }
    }
  } else {
    scm {
    }
  }
}

Upvotes: 0

KeepCalmAndCarryOn
KeepCalmAndCarryOn

Reputation: 9075

You could build the jobs and configure them disabled

job('example') {
    disabled()
}

Then you could activate the job you want to test manually.

The same method is available for other job types too.

Upvotes: 1

Related Questions