Skip to content

Instantly share code, notes, and snippets.

@thikade
Last active February 6, 2023 13:38
Show Gist options
  • Save thikade/5e68a99d611510a521ad74d5f9c88a13 to your computer and use it in GitHub Desktop.
Save thikade/5e68a99d611510a521ad74d5f9c88a13 to your computer and use it in GitHub Desktop.
Jenkins / Groovy language patterns

links

Jenkins Shared Pipelines

killing hanging jenkins jobs

go to script console https://<jenkins>/script, find out JobName and JobNumber, then run:

def jobName = "JobName" // pls change!
def jobNumber = 42      // pls change!
Jenkins.instance.getItemByFullName(jobName)
                .getBuildByNumber(jobNumber)
                .finish(
                        hudson.model.Result.ABORTED,
                        new java.io.IOException("Aborting build")
                );

iterate map "fields"

def fields = env.getEnvironment()
fields.each {
    key, value -> println("${key} = ${value}");
}

log stage that failed in pipeline

post {
    failure {
        echo "error in stage: $last_started"
    }
}

load env variable from file - solution #1

steps {
    script {
        env.MYVAR = readFile('somefile.txt').trim()
    }
    echo "${env.MYVAR}"
}

load env variable from file - solution #2

   environment {
    FILENAME = readFile ...
  }

load variables from file

steps {
    script {
       load "$JENKINS_HOME/.envvars/stacktest-staging.groovy"
       echo "${env.DB_URL}"
       echo "${env.DB_URL2}"
    }
}

load a groovy file and execute it

Example.Groovy

    def exampleMethod() {
        //do something
    }
    def otherExampleMethod() {
        //do something else
    }
    return this

JenkinsFile

    def rootDir = pwd()
    def example = load "${rootDir}@script/Example.Groovy "
    example.exampleMethod()
    example.otherExampleMethod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment