How to get current Build_user in parameterized jenkins project - jenkins

I want to get current Build user name into Active choice reactive parameter groovy script.
I have tried below code but its not working.

Try the following:
try {
def user = hudson.model.User.current().getId()
return [user]
} catch (e)
{
return [e.toString()]
}
It is always better to use try and catch the exception in the groovy scripts, so as to figure out why it is not working.

Related

Jenkinsfile Switch case with contains is throwing CpsCallableInvocation error

I am trying to write a jenkins file with a switch case, where I am trying to use string operations in case. In a regular groovy it is working fine but in JenkinsFile it is throwing errors. What am I missing?
Code
switch (env.UPSTREAM)
{
case { it.contains("SDK") }:
//do something
break
case { it.contains("sample") }:
//do something
break
}
Error
hudson.remoting.ProxyException: CpsCallableInvocation{methodName=call, call=com.cloudbees.groovy.cps.impl.CpsClosureDef#47e13b68, receiver=org.jenkinsci.plugins.workflow.cps.CpsClosure2#3d8cf0c6, arguments=[asjkndakjsd_sample]}
Jenkins uses Groovy CPS to run pipeline scripts, you can read about it here. It's kind of confusing but basically you can't use some of the more complicated groovy functions/commands.
A way to get around this is to use the #NonCPS annotation. You have to create a function outside of your pipeline with that #NonCPS annotation. But in your case you could probably just use simple if statements instead of the switch. For example just create a new variable def upStream = env.UPSTREAM then check each case:
if (upStream.contains("SDK"))
{
// do something
}
else if (upStream.contains("sample"))
{
// do something
}

How to use post build action in a dynamically generated jenkins stage

I'm using Jenkins and I want to add a post-build action to my dynamically generated stages.
I dynamically generate stages by looping over a configuration file I have by doing this:
stage('run list'){
steps {
script {
...
def stages = stagelist.collectEntries {
["${it}": generateStage(it)]
}
...
}
}
}
Where generateStage is defined as:
def generateStage(job){
return {
stage("${job}"){
catchError(){
....
}
post {
...
}
}
}
}
Which works fine for the stages I have currently. However, when I try to add a post-action to my generate stage function I get NoSuchMethod error.
If I could get some help on this it would be greatly appreciated!
When you use static parallel steps it is possible to use the post directive as part of the pipeline syntax, but when you are creating the stages dynamically (in the generateStage) you are doing so by using the scripted pipeline syntax which Does not support the post directive.
What you can do instead is use the scripted pipeline version of the post section using the try catch finally syntax to achieve a similar result to that you would achieve using the post section in a declarative pipeline.
Try something like:
def generateStage(job){
return {
stage("${job}"){
try {
// Your Execution steps
...
// This is equivalent to the 'success' section in the post directive
}
catch(Exception ex) {
// This is equivalent to the 'Failure' section in the post directive
}
finally {
// This is equivalent to the 'always' section in the post directive
}
}
}
}
It is not hundred precent equal, as the try catch will only detect exception and wont detect direct build result change - but it should work for the majority of steps

Jenkins plugin - how to get currently executing job?

I am building a jenkins pipeline plugin (methods to be invoked from a pipeline) and need to get retrieve information about the currently running job, which invoked my methods.
There are a couple of questions I found talking about it, for example here - Jenkins Plugin How to get Job information.
Yet I can't figure out how to use this information. I do have access to the Jenkins instance, but don't have any info about the current project, job, build, etc. How can I get hold of that info?
Note, this is a pipeline steps plugin, there is no perform method in it.
Ok, after search, I finally found the answer in the most obvious of all places - documentation for writing pipeline steps plugins and the corresponding API documentation.
The way to do it is from the Execution class. Inside it, just call getContext(), which returns StepContext, which then has .get method to get the rest of the things you need:
public class MyExecution extends SynchronousNonBlockingStepExecution<ReturnType> {
...
#Override
protected ReturnType run() throws Exception {
try {
StepContext context = getContex();
// get currently used workspace path
FilePath path = context.get(FilePath.class);
//get current run
Run run = context.get(Run.class);
// ... and so on ...
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
...
}

How to handle exceptions in a Jenkins Job DSL seed job?

If I had a Git repository full of Job DSL groovy scripts and a typical seed job e.g.:
job('seed') {
//... scm, triggers etc.
steps {
dsl {
external 'jobs/**/*.groovy'
}
}
//... more config etc.
}
what happens if just one of the job dsl scripts throws an exception for some reason, for example:
job('deliberate-fail') {
throw new Exception("Arrrgggghhh")
}
Is it possible to handle this exception in the seed job or will the whole seed job fail?
If all but one would work - is it possible for the seed job to record an UNSTABLE result rather than FAILURE?
I don't really want one bad apple to spoil the bunch.
Based on Opal's suggestion to use a try-catch, I modifed the job to capture the exception and print an error to the console.
job('deliberate-fail') {
try {
throw new Exception("Arrrgggghhh")
} catch (Exception ex){
println("deliberate-fail job is [UNSTABLE]")
}
}
As I am currently using the Job DSL plugin (and not a Jenkins Pipeline script), I don't think Opal's suggestion to use "currentBuild.result = 'UNSTABLE'" was available to me. After a little digging I found I could use the Text-Finder plugin to search the console for the "[UNSTABLE]" error and change the seed job state accordingly.
job('seed-job') {
steps {
dsl {
external '**/*_jobdsl.groovy'
}
}
publishers {
textFinder(/[UNSTABLE]/, '', true, false, true)
}
}
A bit convoluted but it seems to work!

How to get parameters of another build?

I use parameterized builds in a lot of places. I'd like a pipeline's input to be a build number of a different job. I haven't found a clean way to query Jenkins from within groovy to get the other job's build parameters. Does anybody have a snippet to share?
This works for me in script console
import hudson.model.ParametersAction
def getParams(String project, String buildNumber){
def params=[]
Jenkins.instance.getItem(project).getBuild(buildNumber).getActions(ParametersAction)
.each { action ->
action.getParameters().each {
params << it
}
}
return params
}

Resources