2
votes

I'm using the Docker image: jenkins/jenkins:lts

I've got a number of groovy scripts that are copied into the $JENKINS_HOME/init.groovy.d/ directory during the build of the docker image.

I want to write a script that will create a new Pipeline job, but I'm struggling to find any information on how to do this. All the tutorials seem to be about how to use the pipeline plugin, once the job is created...

The below script is an example of what I'm after, but this is for a Freestyle Project instead of a Pipeline:

#!groovy

import jenkins.model.Jenkins;
import hudson.model.FreeStyleProject;
import hudson.tasks.Shell;
import hudson.triggers.SCMTrigger;

def jenkins = Jenkins.getInstance();
def initJob = jenkins.createProject(FreeStyleProject, 'init-job');

initJob.setDescription('This is a dummy project');
2

2 Answers

3
votes

OK, so I was being really dumb... Pipeline used to be referred to as Workflow, and it tells you that in the UI

enter image description here

So what did it for me was:

#!groovy

import jenkins.model.Jenkins;
import hudson.model.WorkflowJob;
import hudson.tasks.Shell;
import hudson.triggers.SCMTrigger;

def jenkins = Jenkins.getInstance();
def initJob = jenkins.createProject(WorkflowJob, 'init-job');

initJob.setDescription('This is a dummy project');
1
votes

Job DSL Plugin let's you script creation of jobs using groovy. You can keep all your configuration in VCS and tell Jenkins to run Job DSL script to generate all the jobs. Creating pipeline job is as simple as this:

pipelineJob('example') {
    definition {
        cps {
            script(readFileFromWorkspace('project-a-workflow.groovy'))
            sandbox()
        }
    }
}

This example was taken from Job DSL API Viewer.