Skip to content

Instantly share code, notes, and snippets.

@maurorappa
Last active February 28, 2020 13:56
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 maurorappa/8283a914f44e71ded33bd98e1f83fa6e to your computer and use it in GitHub Desktop.
Save maurorappa/8283a914f44e71ded33bd98e1f83fa6e to your computer and use it in GitHub Desktop.
useful Jenkins groovy functions
// find the last successfull build
// you may need to enable these script approvals:
//method hudson.model.Job getBuildByNumber int
//method hudson.model.Job getBuilds
//method hudson.model.Job getLastBuild
//method hudson.model.Job getLastSuccessfulBuild
def lastGreen() {
def buildName = Jenkins.instance.getItemByFullName("my_great_job")
if (buildName) {
return buildName.getLastSuccessfulBuild().getNumber().toString()
}
return 1
}
// find which EC2 slave is running this job
def whereIam(){
sh "wget -qO- 169.254.169.254/2019-10-01/meta-data/hostname"
}
// send to Slack the job completion status
def slackMsg(status) {
color = ''
message = ''
switch (status) {
case "success":
color = "#00FF00"
message = "${env.JOB_NAME} Successful"
break
case "failed":
color = "#EE0000"
message = ":fire: ${env.JOB_NAME} FAILED! :fire:"
break
}
}
// enable these methods:
// method hudson.model.AbstractItem setDescription java.lang.String
// staticMethod org.codehaus.groovy.runtime.EncodingGroovyMethods encodeBase64 byte[]
def setAuth(){
s = "$USER:$PWD"
auth_token = s.bytes.encodeBase64().toString()
return auth_token
}
// add a sleep on the current task
def Sleep(){
Random random = new Random()
Thread.sleep(random.nextInt(30)*1000)
}
// don't run the build if a specific commit message is present
def IgnoreCommittedMessage() {
def Check = sh(script: "git log -n 1 --oneline| grep 'do not build' |wc -l", returnStdout: true).toInteger()
if (Check == 1) {
currentBuild.result = 'NOT_BUILT'
error("Skipping build")
}
}
//plus remember you can use
// def fileContents = readJSON file:'list.txt'
// writeJSON file: 'list.txt', json: jsonOut
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment