Skip to content

Instantly share code, notes, and snippets.

@aespinosa
Last active September 2, 2021 13:55
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save aespinosa/6bd1b8d2d65aed2179de to your computer and use it in GitHub Desktop.
Save aespinosa/6bd1b8d2d65aed2179de to your computer and use it in GitHub Desktop.
create a jenkins job in the script console
import jenkins.model.Jenkins;
import hudson.model.FreeStyleProject;
import hudson.tasks.Shell;
job = Jenkins.instance.createProject(FreeStyleProject, 'job-name')
job.buildersList.add(new Shell('echo hello world'))
job.save()
build = job.scheduleBuild2(5, new hudson.model.Cause.UserIdCause())
build.get() # Block until the build finishes
generatedJobs = build.getAction(javaposse.jobdsl.plugin.actions.GeneratedJobsBuildAction).getItems()
# FIXME skip .scheduleBuild2() on Folder jobs
generatedJobs.each { j -> j.scheduleBuild2(5, new hudson.model.Cause.UserIdCause()) }
@peterjenkins1
Copy link

Thank you so much! This is way way simpler than using XML, APIs, or the whole Job DSL plugin syntax. I don't understand why there are not more examples like this online.

@cjacobs-at-comscore
Copy link

Now, how to create a groovy build step? Specifically a system groovy build step? I'm not a java developer and google isn't helping me.

@djgio02
Copy link

djgio02 commented Jan 7, 2020

is there a way I can add the SCM section in this script? something like:
job.buildersList.add (new GitSCM'repo.git'))
or what would be the right sintax for this request?

@aespinosa
Copy link
Author

@djgio02 you can figure it out by looking at the javadocs of the git-scm jenkins plugin.

@tlopo
Copy link

tlopo commented Sep 2, 2021

I spent some time trying to figure out the SCM part, I am adding a comment here so it may help someone in the future:

import jenkins.model.Jenkins
import hudson.model.FreeStyleProject
import hudson.model.Label
import hudson.tasks.BatchFile
import hudson.plugins.git.GitSCM
import hudson.plugins.git.BranchSpec
  
def scm = new GitSCM('https://github.com/tlopo/WinAppDriver-Sample.git')
scm.branches = [new BranchSpec("*/master")]
  
command = """ 
powershell -Command npm install -g appium
powershell -Command reg add "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\AppModelUnlock" /t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1"
powershell "Start-Process 'cmd' -ArgumentList '/c \\"C:\\Program Files (x86)\\Windows Application Driver\\WinAppDriver.exe\\" 127.0.0.1 4723/wd/hub  1>winappdriver_out.log 2>winappdriver_err.log' -WindowStyle Hidden
.\\mvnw.cmd test
"""
  
job = Jenkins.instance.createProject(FreeStyleProject, 'winappdriver-poc')
job.setScm scm
job.buildersList.add(new BatchFile(command))
job.setAssignedLabel( Jenkins.instance.getLabel('win'))
job.save()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment