Jenkins Groovy snippets

Материал из noname.com.ua
Перейти к навигацииПерейти к поиску

Upstream Job (вызвовшая текущую), частный случай

node() {
    stage('downstream') {
        def upstream = currentBuild.rawBuild.getCause(hudson.model.Cause$UpstreamCause)
        echo upstream?.shortDescription
    }
}

Получение тектовых параметров от билда (например в downstream job что бы не передавать их

import hudson.model.*
import hudson.maven.*
import hudson.tasks.*
import jenkins.model.Jenkins
import hudson.maven.reporters.*
import hudson.plugins.emailext.*

def job_name = "some-existing-job-name"
def build_number = 12345 // existing build

def getParametersFromBuild(jobName, buildNumber, parameterType) {
    // Parameter type is class, possible values are
    // StringParameterValue
    // TextParameterValue
    def job_parameters = [:]
    // Get Job class by fullName
    //println(jobName)
    def job_instance = Jenkins.getInstance().getItemByFullName(jobName, hudson.model.Job.class)
    //println("job: " + job_instance +  "\n")
    //println(job_instance.getClass().getName())

    // Get build instance using build number
    // build nummbaer can be obtained from upstream job
    job_build_instance = job_instance.getBuildByNumber(buildNumber)
    //println("build_instance:" + job_build_instance)
    //println(job_build_instance.getAllActions().getClass().getName())
    job_all_build_instance_parameters_action = job_build_instance.getAllActions().findAll{ it instanceof ParametersAction }
    //println("job_all_build_instance_parameter_actions: " + job_all_build_instance_parameters_action)
    //println(job_all_build_instance_parameters_action.getClass().getName())

    //job_build_instance_parameters_action is list of classes 
    job_all_build_instance_parameters_action.each { parameters_action ->
        //println("parameters_action: " + parameters_action)
        //println(parameters_action.getClass().getName())
        // Get all parameters from ParametersAction
        all_parameters = parameters_action.getAllParameters()
        // list all parameters
        //all_parameters.each { generic_parameter ->
            //println(generic_parameter)
            //println(generic_parameter.getClass())
            //println(generic_parameter.getClass().getName())
        
        //}
        if (parameterType == "string") {
            all_parameters.findAll{ it instanceof hudson.model.StringParameterValue }.each { string_parameter ->
                //println("string_parameter: " + string_parameter)
                //println(string_parameter)
                //println(string_parameter.toString())
                //str = string_parameter.toString()
                //println(str)
                string_parameter_name = string_parameter.getName()
                string_parameter_value = string_parameter.getValue()
                job_parameters[string_parameter_name] = string_parameter_value
                //println(string_parameter.getDefinition())
                //println("------------------")

            
            }
        } else if (parameterType == "text") {
            all_parameters.findAll{ it instanceof hudson.model.TextParameterValue }.each { text_parameter ->
                // Not implemented
                println("text_parameter: " + text_parameter)
                println(text_parameter)
            
            }
        } else {
            return [:]
        }
    }
    return job_parameters
}

upstream_job_text_parameters = getParametersFromBuild(job_name, build_number, "string")
println(upstream_job_text_parameters)
upstream_job_text_parameters.each { k, v -> 
    println("=====")
    println("KEY=   " + k)
    println("VALUE= " + v)
    println("=====")
}

Получение Upstream Job и причины вызоыв билда (не безопасен и вызывает ошибки сериализации в неопределеных случаях)

@NonCPS
def findBuildCause(build) {
    def causes = []
    //Check if the build was triggered by some jenkins project(job)
    upstreamcause = build.getCause(hudson.model.Cause.UpstreamCause.class)
    //println("upstreamcause")
    if (upstreamcause != null) {
        job = Jenkins.getInstance().getItemByFullName(upstreamcause.getUpstreamProject(), hudson.model.Job.class)
        //println("job")
        //println(job)
        if (job != null) {
            upstream = job.getBuildByNumber(upstreamcause.getUpstreamBuild())
            if (upstream != null) {
                //return upstream
                causes.add(upstream)
            }
        }
    }
    //Check if the build was triggered by SCM change
    scmCause = build.getCause(hudson.triggers.SCMTrigger.SCMTriggerCause)
    //println("scmCause")
    //println(scmCause)
    if (scmCause != null) {
        //return scmCause.getShortDescription()
        causes.add(upstream)
    }
    
    //Check if the build was triggered by timer
    timerCause = build.getCause(hudson.triggers.TimerTrigger.TimerTriggerCause)
    //println("timerCause")
    //println(timerCause)

    if (timerCause != null) {
        //return timerCause.getShortDescription()
        causes.add(imerCause)
    }
    //Check if the build was triggered by some jenkins user
    usercause = build.getCause(hudson.model.Cause.UserIdCause.class)
    //println("usercause")
    //println(usercause)
    if (usercause != null) {
        //return usercause.getUserId()
        causes.add(usercause)
    }
    return causes
}

def build_description = ""
build_causes.each { build_cause -> 
    println("BUILD_CAUSE")
    println(build_cause)
    println("CLASS " + build_cause.getClass())
    println("CLASS_NAME:" + build_cause.getClass().getName())
    if ( build_cause instanceof org.jenkinsci.plugins.workflow.job.WorkflowRun )  {
        build_description = "Build Caused by: \n" + "Build Name: " + build_cause.getFullDisplayName() + "Build Number " + build_cause.getNumber() + "\n"
    }

    if ( build_cause instanceof hudson.model.Cause$UserIdCause ) {
        build_description = build_description + "User: " + build_cause.getUserName() + "(" + build_cause.getUserId() + ")\n"
    }

}

currentBuild.description = build_description

Получение Upstream Job и причины вызоыв билда (предположительно более безопастный)

@NonCPS
def setBuildDescription() {

    def build_description = ""
    def causes = []
    def cuse

    //println("upstreamcause")
    if (currentBuild.getRawBuild().getCause(hudson.model.Cause.UpstreamCause.class) != null) {
        if (Jenkins.getInstance().getItemByFullName(currentBuild.getRawBuild().getCause(hudson.model.Cause.UpstreamCause.class).getUpstreamProject(), hudson.model.Job.class) != null) {
            if (Jenkins.getInstance().getItemByFullName(currentBuild.getRawBuild().getCause(hudson.model.Cause.UpstreamCause.class).getUpstreamProject(), hudson.model.Job.class).getBuildByNumber(currentBuild.getRawBuild().getCause(hudson.model.Cause.UpstreamCause.class).getUpstreamBuild()) != null) {
                //return upstream
                causes.add(Jenkins.getInstance().getItemByFullName(currentBuild.getRawBuild().getCause(hudson.model.Cause.UpstreamCause.class).getUpstreamProject(), hudson.model.Job.class).getBuildByNumber(currentBuild.getRawBuild().getCause(hudson.model.Cause.UpstreamCause.class).getUpstreamBuild()))
            }
        }
    }
    
    if (currentBuild.getRawBuild().getCause(hudson.triggers.SCMTrigger.SCMTriggerCause) != null) {
        causes.add(currentBuild.getRawBuild().getCause(hudson.triggers.SCMTrigger.SCMTriggerCause))
    }
    
    if (currentBuild.getRawBuild().getCause(hudson.triggers.TimerTrigger.TimerTriggerCause) != null) {
        causes.add(currentBuild.getRawBuild().getCause(hudson.triggers.TimerTrigger.TimerTriggerCause))
    }
    
    if (currentBuild.getRawBuild().getCause(hudson.model.Cause.UserIdCause.class) != null) {
        causes.add(currentBuild.getRawBuild().getCause(hudson.model.Cause.UserIdCause.class))
    }
    if (causes instanceof Serializable ) {
        println(causes + " is Serializable")
    }

    for (i=0; i<causes.size(); i++) {
        def index = i
        def build_cause=causes[index]
        println("BUILD_CAUSE")
        println(build_cause)
        println("CLASS " + build_cause.getClass())
       println("CLASS_NAME:" + build_cause.getClass().getName())
        if ( build_cause instanceof org.jenkinsci.plugins.workflow.job.WorkflowRun )  {
            build_description = "Build Caused by: \n" + "Build Name: " + build_cause.getFullDisplayName() + "Build Number " + build_cause.getNumber() + "\n"
        }

        if ( build_cause instanceof hudson.model.Cause$UserIdCause ) {
            build_description = build_description + "User: " + build_cause.getUserName() + "(" + build_cause.getUserId() + ")\n"
        }
        if ( build_cause instanceof hudson.triggers.TimerTrigger.TimerTriggerCause ) {
            build_description = "Triggered by timer: " + build_cause.getShortDescription()
        }
    }
    currentBuild.description = build_description
}