Jenkins Groovy snippets: различия между версиями
Материал из noname.com.ua
Перейти к навигацииПерейти к поискуSirmax (обсуждение | вклад) (→111) |
Sirmax (обсуждение | вклад) |
||
Строка 1: | Строка 1: | ||
[[Категория:Jenkins]] |
[[Категория:Jenkins]] |
||
[[Категория:CICD]] |
[[Категория:CICD]] |
||
+ | [[Категория:Groovy]] |
||
− | |||
+ | [[Категория:GroovyDSL]] |
||
=Upstream Job (вызвовшая текущую), частный случай= |
=Upstream Job (вызвовшая текущую), частный случай= |
Текущая версия на 10:41, 28 апреля 2022
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 }
Получение списка нод по лейблу
@NonCPS def hostNames(label) { def nodes = [] jenkins.model.Jenkins.instance.computers.each { c -> if (c.node.labelString.contains(label)) { nodes.add(c.node.selfLabel.name) } } return nodes }
Параллельный запуск
def parallelTasks = [:] def slaveNodes= hostNames('lable') def housekeeperJobName = "job to run" setBuildDescription() for (i=0; i<slaveNodes.size(); i++) { def index = i println(slaveNodes[index]) parallelTasks[slaveNodes[index]] = { build( job: housekeeperJobName, parameters: [ [ $class: 'StringParameterValue', name: 'SLAVE_NAME', value: slaveNodes[index] ]] ) } } parallel parallelTasks
Получение причины билда рекурсивно до изначальной причины запуска
DOWNSTREAM_JOB="020-kilda-experemental-jobs/99-test-downstream-job-2" CLUSTER="TEST" RELEASE_DATA="RELEASE_DATA" node('master') { println(getBuildUser()) build( job: DOWNSTREAM_JOB, parameters: [ // ChoiceParameterValue [$class: 'StringParameterValue', name: 'CLUSTER', value: CLUSTER], [$class: 'StringParameterValue', name: 'RELEASE_DATA', value: RELEASE_DATA], ], propagate: true ) } @NonCPS def getUpstreamJob(def build) { println("build") println(build) println(build.getClass().getName()) def upstream_cause = build.getCause(hudson.model.Cause$UpstreamCause) println("upstream_cause") println(upstream_cause) println(upstream_cause.getClass().getName()) println("---------------------------------") if ( upstream_cause != null ) { def wokrflow_job = Jenkins.getInstance().getItemByFullName(upstream_cause.getUpstreamProject(), hudson.model.Job.class) def workflow_run = wokrflow_job.getBuildByNumber(upstream_cause.getUpstreamBuild()) println("wokrflow_job") println(wokrflow_job) println(wokrflow_job.getClass().getName()) println("---------------------------------") println("workflow_run") println(workflow_run) println(workflow_run.getClass().getName()) println("---------------------------------") println("") return getUpstreamJob(workflow_run) } else { return build } } @NonCPS def getCasue(def workflow_run) { try { def user_cause = workflow_run.getCause(Cause.UserIdCause) println("user_cause") println(user_cause.getClass().getName()) if (user_cause != null) { return user_cause } } catch(Err) { println("Failed to get UserIdCause") println(Err) } try { def time_trigger_cause = workflow_run.getCause(hudson.triggers.TimerTrigger.TimerTriggerCause) println("time_trigger_cause") println(time_trigger_cause.getClass().getName()) if (time_trigger_cause != null) { return time_trigger_cause } } catch(Err) { println("Failed to get hudson.triggers.TimerTrigger.TimerTriggerCause") println(Err) } try { def scm_trigger_cause = workflow_run.getCause(hudson.triggers.SCMTrigger.SCMTriggerCause) println("scm_trigger_cause") println(scm_trigger_cause.getClass().getName()) if (scm_trigger_cause != null) { return scm_trigger_cause } } catch(Err) { println("Failed to get hudson.triggers.SCMTrigger.SCMTriggerCause") println(Err) } throw new Exception("Can't build cause") } @NonCPS def getBuildUser() { def upstream = getUpstreamJob(currentBuild.rawBuild) println("upstream") println(upstream) println(upstream.getClass().getName()) println("---------------------------------") def cause = getCasue(upstream) println("cause") println(cause) println(cause.getClass().getName()) println("---------------------------------") if ( cause instanceof hudson.model.Cause$UserIdCause ) { return cause.getUserName().toString() } else if ( cause instanceof hudson.triggers.TimerTrigger$TimerTriggerCause ) { return "TRIGGERED_BY_TIMER_TRIGGER" } else { throw new Exception("Can't find user") } return "TESTING" }