Initializing Jenkins 2.0 with pipeline in init.groovy.d script - jenkins

For automation, I would like to initialize a Jenkins 2.0 instance with a pipeline job. I want to create a Groovy script that is copied to the /usr/share/jenkins/ref/init.groovy.d/ folder on startup. The script should create a Jenkins 2.0 Pipeline job for processing a Jenkinsfile from SCM.
I cannot find the relevant Javadoc for the 2.0 pipeline classes or examples of how to do this.
Previously, using Job DSL to create a pipeline, I used a Groovy script to create a FreeStyleProject with an ExecuteDslScripts builder. That job would then be the Job DSL seed job.
One option is to use an init script to create a Job DSL seed job to create a Jenkins 2.0 pipeline. It just seems unnecessarily complex.
I am experimenting in this repo: https://github.com/martinmosegaard/vigilant-sniffle

With Job DSL 1.47 (to be released soon) you can use the Job DSL API directly from the init script without the need to create a seed job.
import javaposse.jobdsl.dsl.DslScriptLoader
import javaposse.jobdsl.plugin.JenkinsJobManagement
def jobDslScript = new File('jobs.groovy')
def workspace = new File('.')
def jobManagement = new JenkinsJobManagement(System.out, [:], workspace)
new DslScriptLoader(jobManagement).runScript(jobDslScript.text)
See PR #837 for details.

If you only need to create one simple pipeline job, you can use the Jenkins API. But that really only works well when creating one simple job, for a complex setup you need some abstraction like Job DSL.
Start here: http://javadoc.jenkins-ci.org/jenkins/model/Jenkins.html#createProject(java.lang.Class,%20java.lang.String).
Example:
import jenkins.model.Jenkins
import org.jenkinsci.plugins.workflow.job.WorkflowJob
WorkflowJob job = Jenkins.instance.createProject(WorkflowJob, 'my-pipeline')
Then you need to populate the job, e.g. setting a flow definition.
Or you can wait for the System Config DSL Plugin to be ready. But it has not been released yet and I'm not sure if it can create jobs.

Related

How can i add a post build step to an existing job using job dsl?

How can i add a post build step to an existing job using job dsl ?
Note: I need to append to the existing job. It should not delete the existing steps.
You can not append something to an existing job. You need to code the complete job definition in Job DSL.
But you can use the Jenkins API to add a post build step:
FreeStyleProject job = Jenkins.instance.getItem('job-a')
job.publishersList << new hudson.tasks.BuildTrigger('job-b', false)
You can try the code in Jenkins Script Console.
Note that a post build step will be added each time you run the script. If you code the complete job definition in Job DSL, the Job DSL engine will modify the job only if the script changed or your job configuration does not match the definition.

How does DSL extension in Jenkins plugin work

I want to create DSL extension for my Jenkins plugin (built using maven) just like in the example of Docker plugin for Jenkins. I see that the groovy file Docker.groovy is in: src/main/resources/org/jenkinsci/plugins/docker/workflow/Docker.groovy
Does this groovy file have to be within org.jenkinsci.plugin.docker.workflow, or can I just put it inside resources? What is the difference?
Also, If I define my DSL extension within the groovy file in this manner is the DSL extension available to call implicitly in the pipeline file?
In order to make a step available in the Pipeline DSL through your plugin, you need to define a subclass of Step that performs the needed task. This can be completely done within Java, and is the preferred method for adding expanding the Pipeline DSL within a Jenkins plugin.
The Docker example you linked is unusual in this instance, and doesn't define a typical Pipeline DSL step (the docker directive in Pipeline functions like a cross between an agent, a step and a context block). Furthermore, it appears to include a Java class that loads the Groovy script dynamically, which acts as the entry point into the directive.
Groovy can be used to expand the Pipeline DSL; however this is done within the context of a shared library, which is meant to be more of a boilerplate reducing tool to be used internally.

Extending the Jenkins Groovy DSL

How can I add/edit new code to my Jenkins instance that would be accesible in a DSL script? Context follows
I've inherited a Jenkins instance. Part of this inheritance includes spending the night in a haunted house writing some new automation in groovy via the Jobs DSL plugin. Since I'm fearful of ruining our jenkins instance, my first step is setting up a local development instance.
I'm having trouble running one of our existing DSL Scripts on my local development instance -- my builds on the local server fail with the following in the Jenkins error console.
Processing DSL script jobs.groovy
ERROR: startup failed:
jobs.groovy: 1: unable to resolve class thecompanysname.jenkins.extensions
The script in question starts off like this.
import thecompanysname.jenkins.extensions
use(extensions) {
def org = 'project-name'
def project = 'test-jenkins-repo'
def _email = 'foo#example.com'
So, as near I can tell, it seems like a predecesor has written some custom Groovy code that they're importing
import thecompanysname.jenkins.extensions
What's not clear to me is
Where this code lives
How I can find it in our real Jenkins instance
How I can add to to my local instance
Specific answers are welcome, as our here's how you can learn to fish answers.
While there may be other ways to accomplish this, after a bit of poking around I discovered
The Jenkins instance I've installed has an older version of the Jobs DSL plugin installed.
This version of the Jobs DSL plugin allowed you to set an additional classpath in your Process DSL Builds job section that pointed to additional jar files.
These jar files can give you access to additional classes in your groovy scripts (i.e. thecompanysname.jenkins.extensions)
Unfortunately, more recent versions of the Jobs DSL plugin have removed this option, and it's not clear if it's possible to add it back. That, however, is another question.
Configure Global Security -> uncheck "Enable script security for Job DSL
scripts".
works for me

How to pass env vars to a MultibranchPipelineJob created by Jenkins Job DSL?

I am creating a MultibranchPipelineJob with Jenkins Job DSL. I want to pass some environment variables to the job, but I can't figure out how to do that from the documentation.
MultibranchPipeline Job no longer support parameters
You can use Folder Properties Plugin to set your Env variables, which can be accessed by all the jobs within that folder. https://plugins.jenkins.io/folder-properties/
However, the MultiBranch pipeline job has a lot of performance issues so we moved away from multibranch pipeline jobs. We wrote a DSL job that would act as a multibranch pipeline job - which will scan through the git branches and create Simple pipeline jobs as needed.
You pass them as parameters like this:
parameters {
stringParam("MyVariable1", "my-value1")
stringParam("MyVariable2", "${my-dynamic-value2}")
}
Then consume them in the job using parameters or environment (both work equally) as this:
echo "my vars are ${parameters.MyVariable1} or ${env.MyVariable2}"

What are seed jobs in Jenkins and how does it work?

What are seed jobs in Jenkins and how does it work ?
Can we create a new job from seed job without using github ?
That depends on context. Jenkins itself does not provide "seed jobs".
There's plugins that allow creating jobs from other jobs, like the excellent Job-DSL plugin. With that, you can create jobs where a groovy script creates a larger number of jobs for you.
The Job-DSL plugin refers to those jobs as "seed jobs" (but they're regular freestyle or pipeline jobs). The Job-DSL plugin does not require a github connection.
The seed job is a normal Jenkins job that runs the Job DSL script; in turn, the script contains instructions that create additional jobs. In short, the seed job is a job that creates more jobs. In this step, you will construct a Job DSL script and incorporate it into a seed job. The Job DSL script that you’ll define will create a single freestyle job that prints a 'Hello World!' message in the job’s console output.
A Job DSL script consists of API methods provided by the Job DSL plugin; you can use these API methods to configure different aspects of a job, such as its type (freestyle versus pipeline jobs), build triggers, build parameters, post-build actions, and so on. You can find all supported methods on the API reference site.
The jobs we used for creating new jobs are called Seed Jobs and this seed job generates new jobs using Jenkins files (using JobDSL plugin).
Here, we disabling this feature (Enable script security for Job DSL scripts)
Jenkins Dashboard→ Manage Jenkins → Configure Global Security
Way to create seed job :
JobDSL scripts for generating new jobs.
Job1.groovy
job("Job1"){
description("First job")
authenticationToken('secret')
label('dynamic')
scm {
github('Asad/jenkins_jobDSL1', 'master')
}
triggers {
gitHubPushTrigger()
}
steps {
shell ('''
echo "test"
''')
}
}
buildPipelineView('project-A') {
title('Project A CI Pipeline')
displayedBuilds(5)
selectedJob('Job1')
showPipelineParameters()
refreshFrequency(60)
}
and create same way others Job2.groovy and so on.
For Jenkins Job DSL documentation:-
Follow https://jenkinsci.github.io/job-dsl-plugin/
Think about a job - what is it actually ?
It is actually just a java/jre object that represents like this
How you generates such job/build ?
Configure Jenkins UI -> rest api to Jenkins url -> Jenkins service receive your call on the relevant endpoint -> calling to the relevant code/method and generate this new job
How Seed job will make it ?
Configure seed job on Jenkins UI only once -> run this seed job - > this code run against the internal Jenkins methods and skip all the manual process describes above
Now, when your code can talk directly to Jenkins code , things are much easier.just update your code on the relevant repo - and you are done

Resources