Skip to content

Instantly share code, notes, and snippets.

@rsandell
Created October 5, 2015 17:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsandell/6a42cc15b748a41c1fe5 to your computer and use it in GitHub Desktop.
Save rsandell/6a42cc15b748a41c1fe5 to your computer and use it in GitHub Desktop.
A script that runs a groovy file as a workflow on a locally running Jenkins.
#!/usr/bin/env groovy
/*
* The MIT License
*
* Copyright (c) 2015 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
A script that runs a groovy file as a workflow on a locally running Jenkins.
Can be used as an external tool or run configuration in your IDE.
Takes the file to run as the first and only argument.
set JENKINS_URL if your jenkins instance is not running on http://localhost:8080
set JENKINS_HOME if your jenkins instance has a different home than $HOME/.jenkins
To set up as an external tool in IntelliJ IDEA (v 14.1.1)
//You need a "proper" groovy environment that can run this script from the command line
Open File -> Settings
Go to Tools/External Tools
Click the + to Add
Name: Jenkins WF
Description: Run file as Jenkins workflow
Program: path/to/this/wf-jenkins.groovy
Parameters: $FilePath$
It should now show up in the "External Tools" sub menu if you right click in an opened file in the editor
*/
import groovy.xml.XmlUtil
final String projectSkel = '''<?xml version='1.0' encoding='UTF-8'?>
<flow-definition plugin="workflow-job@1.10">
<actions/>
<description></description>
<logRotator class="hudson.tasks.LogRotator">
<daysToKeep>-1</daysToKeep>
<numToKeep>20</numToKeep>
<artifactDaysToKeep>-1</artifactDaysToKeep>
<artifactNumToKeep>-1</artifactNumToKeep>
</logRotator>
<keepDependencies>false</keepDependencies>
<properties/>
<definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps@1.10">
<script>SCRIPT
</script>
<sandbox>false</sandbox>
</definition>
<triggers/>
</flow-definition>'''
if (args.length <= 0) {
println "Need a file for first argument!"
System.exit(1)
}
String jenkinsUrl = System.getenv("JENKINS_URL")
if (jenkinsUrl == null) {
println "JENKINS_URL environment not set using localhost:8080"
jenkinsUrl = "http://localhost:8080"
}
String jenkinsHome = System.getenv("JENKINS_HOME")
if (jenkinsHome == null) {
jenkinsHome = System.getProperty("user.home") + "/.jenkins"
}
if (new File(jenkinsHome).exists()) {
println("Using Jenkins Home ${jenkinsHome}")
} else {
println("Can't find Jenkins Home! tried ${jenkinsHome} please set JENKINS_HOME env var.")
System.exit(1)
}
File flow = new File(args[0])
String jobName = flow.getName().substring(0, flow.getName().lastIndexOf('.'))
def xml = XmlSlurper.newInstance().parse(new StringBufferInputStream(projectSkel))
xml.definition.script = flow.readLines().join('\n')
String javaHome = System.getProperty("java.home")
boolean exec(String cmd, def inputBody = null) {
Process proc = cmd.execute()
if (inputBody != null) {
inputBody(proc.getOutputStream())
}
proc.consumeProcessOutput(System.out, System.err)
def exit = proc.waitFor()
if (exit != 0) {
System.exit(exit + 100)
return false
} else {
return true
}
}
String cli = "${javaHome}/bin/java -jar ${jenkinsHome}/war/WEB-INF/jenkins-cli.jar -s ${jenkinsUrl}"
this.exec("${cli} groovy =") { OutputStream o ->
String createScript = "if (jenkins.model.Jenkins.instance.getItem(\"${jobName}\") == null) jenkins.model.Jenkins.instance.createProject(org.jenkinsci.plugins.workflow.job.WorkflowJob.class, \"${jobName}\")"
PrintStream ps = new PrintStream(o)
ps.write(createScript)
ps.flush()
ps.close()
}
this.exec("${cli} update-job ${jobName}") { OutputStream o ->
XmlUtil xmlUtil = new XmlUtil()
xmlUtil.serialize(xml, o)
o.close()
}
//The cli command build can't start workflows at the moment
final String runScript = """import hudson.cli.BuildCommand
import hudson.model.CauseAction
import hudson.model.queue.QueueTaskFuture
import jenkins.model.Jenkins
import org.jenkinsci.plugins.workflow.job.WorkflowJob
Jenkins jenkins = Jenkins.instance;
WorkflowJob job = jenkins.getItem(\"${jobName}\")
QueueTaskFuture f = job.scheduleBuild2(0, new CauseAction(new BuildCommand.CLICause(Jenkins.getAuthentication().getName())));
def run = f.waitForStart()
println(\"Started \${run.getFullDisplayName()}\")
run.writeWholeLogTo(stdout)
f.get() // wait for the completion
println(\"Completed \${run.getFullDisplayName()} : \${run.getResult()}\")
"""
this.exec("${cli} groovy =") { OutputStream o ->
PrintStream ps = new PrintStream(o)
ps.write(runScript)
ps.flush()
ps.close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment