I am new to Jenkins. I am trying some basic functions using radio buttons.
In the below code it seems to have a problem displaying prevJob value. When i select either radio buttons, no value is returned (value should be display to the right of HANDLE_VERSION (Image provided)). However the code works in Jenkin's Script Console. I tried some other functions such as def
jobName = this.binding.jenkinsProject.name
And that worked and return the current job name when selecting the radio button.
Why is that? Eventually i would like to get the prev build version and handle some logic which will adjust the build version for the user before kicking off the job. Any clarity/help would be greatly appreciative. Thank you!
switch(MAJOR_OR_MINOR){
case~/.*Major.*/:
//vOption="Major"
def jobName = "Test"
def job = Jenkins.instance.getItem(jobName)
def prevJob = (job.getBuilds()[0]).toString()
return "<b>${prevJob}</b>"
break
case~/.*Minor.*/:
//vOption="Minor"
def jobName = "Test"
def job = Jenkins.instance.getItem(jobName)
def prevJob = (job.getBuilds()[0]).toString()
return "<b>${prevJob}</b>"
break
}
Here are some screenshots:
Solved: Sorry, i realized that i did not import my packages.
import hudson.model.*;
import jenkins.model.Jenkins
Related
I tried my best to search and make sure this is not duplicate questions. but didn't get any. so writing it now.
We have Daily Scheduled jobs which runs in night time for our application. so we have our support team who actually make sure all jobs went successfully every night. if not raise a ticket/concern.
Now, Support team checks all this Jobs by going to Jenkins.
We are now looking for option to make this monitoring automated by sending in mail to all stakeholders.
Being said that I have 10 jobs which I want all those jobs listed in a table with Status of execution of last night and send to group of people.
How can we achieve this? is there any Jenkins Plugin which can help us?
Thanks in Advance.
Unfortunately, I was not allowed to use API in our Jenkins due to some security constraints.
so had to go with below solution.
(have added only stage which we need for getting job status. feel free to edit/update as you need)
stage('Get status of Jobs') {
steps {
script {
env.mailText=""
def mailText = "============================================= \n"
//Add your all jobs name in a list.
allDailyJobs = ['Prod/Daily-Jobs/dbBackups', 'Prod/Daily-Jobs/productImport']
allDailyJobs.each() { jobName ->
//Remove the path prefix to get only Job name (to mention in mail report)
def regex = ~"^Prod/Daily-Jobs/"
String just_job_name = jobName - regex
// Get the Job Latest Details
def job_number = getBuildNumber(jobName)
def job_result = getBuildStatus(jobName)
//echo is paragraph format with lines sepearators
mailText = mailText + " Daily Job Name => ${just_job_name} \n"
mailText = mailText + " Build number => ${job_number} \n"
mailText = mailText + " Build Status => ${job_result} \n"
mailText = mailText + " ============================================= \n\n"
}
env.mailText = mailText
}
}
}
// Get the Last Build Numnber for the job.
#NonCPS
def getBuildNumber(String jobName) {
def job = jenkins.model.Jenkins.instance.getItemByFullName(jobName)
return job.getLastBuild().getNumber()
}
// Get the Status of the Job
#NonCPS
def getBuildStatus(String jobName) {
def job = jenkins.model.Jenkins.instance.getItemByFullName(jobName)
return job.getLastBuild().getResult().toString()
}
This stage gives "env.mailText" value which has all jobs details you need. we can use this one to send in mail or chats or to any Hooks.
Important point : this would require script approval in Jenkins to execute the task. so please make sure you have right access for it.
(to avoid this happening again and again, use it without sandbox checkout)
this is how it looks in mail.
I have some requirements to check when user is creating a new issue. So on creation if they select particular component say "ABC", then duedate should be a mandatory field and if they forget to add that then it should throw an error. And the duedate should always be greater than 3 weeks than the today's date, if not it should display an error and until unless it's greater than 3 weeks they can not create issue.
I did see some inbuilt validators for required fields and duedate but it's applying to all component whereas I need only for particular component. Any suggestion/help ?
Thanks in advance!
If you are using Script runner Plugin, This can be achieved by writing a custom behavior.
For example Script runner Behavior:
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.user.util.UserUtil
import java.util.Date.*
def componentField= getFieldByName("component/s")
def dueDate= getFieldByName("Due Date")
dueDate.setRequired(false)
dueDateValue = dueDate.getValue() as Date
def today = new Date()
def threeWeekDate= today.plus(21)
if (componentField.getValue() == "ABC") {
dueDate.setRequired(true)
}
if(dueDateValue.before(threeWeekDate)){
dueDate.setError("You must choose a date after 3 weeks from today")
}
I'm struggling a little creating a timestamp in a format that I want using a scripted pipeline in Jenkins. Here's my code from the pipeline:
def cal = Calendar.instance
def dateFormat = 'YYYYMMDD-hhmmss'
def timeZone = TimeZone.getTimeZone('CST')
def timeStamp = cal.time.format(dateFormat,timeZone)
println "Timestamp is: ${timeStamp}"
env.BUILD_TIMESTAMP = timeStamp
When I run via Jenkins, I get the following:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: unclassified field java.util.GregorianCalendar time
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.unclassifiedField(SandboxInterceptor.java:387)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:371)
I've seen mention of similar issues with different fields online, but the workaround of adding it to scriptapproval.xml (and restarting Jenkins) doesn't seem to be working.
Anyone have a method of generating a timestamp in a format similar to what I'm trying to do?
I figured out a way around it. I was accessing the field time directly. If I change the call from cal.time to cal.getTime() Jenkins behaves a lot better. I consolidated it into a one-liner, but the functionality's the same:
def timeStamp = Calendar.getInstance().getTime().format('YYYYMMdd-hhmmss',TimeZone.getTimeZone('CST'))
Thanks to those that had a look.
Or use Date() formatted with SimpleDateFormat():
import java.text.SimpleDateFormat
def dateFormat = new SimpleDateFormat("yyyyMMddHHmmss")
def date = new Date()
def timestamp = dateFormat.format(date)
a question about the pre-send script possibility of email-ext:
At the moment, this is the "Default Content" of the Email Notification:
<h3>$PROJECT_NAME - Build # $BUILD_NUMBER - $BUILD_STATUS</h3>
<p>
Check console output at $BUILD_URL/console to view the results.
</p>
...
<hr/>
<b>Changes since last build</b><br/>
<div style="padding-left: 15px; padding-bottom: 15px;">
${CHANGES,format="<div><b>%a</b></div><div style=\"padding-left:30px;\"> — “<em>%m</em>”</div><br/>"}
</div>
This will include the commit messages in the result email... and as we are giving the Jira issue id with every commit, it would be nice to replace the Jira issue id, e.g. TESTPROJECT-1234 with a link to it.
Can somebody help me, to achieve this behavior?
The best way to do this is to use a regex, right? like
(TESTPROJECT-[1-9][0-9]*)
and replace it with
$1
But at the moment I have no glue, how to use groovy and the pre-send script to do this. :(
You don't even need regular expression. See this script example: https://github.com/jenkinsci/email-ext-plugin/blob/master/src/main/resources/hudson/plugins/emailext/templates/groovy-html.template that shows you how to loop over your changeset.
if it is still relevant, below is the script for release note with links as you was looking for
import hudson.model.*;
import hudson.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
println build.getEnvVars()['JiraReleaseNotes']
def txt = build.getEnvVars()['JiraReleaseNotes']
def JiraReleaseNotes2 = txt.replaceAll(/# ([^]]*)/){ all, it ->
"</br>$all"
}
def JiraReleaseNotes1 = JiraReleaseNotes2.replaceAll(/- \[([^]]*)]/){ all, it ->
"</br><li>${it}"
}
println JiraReleaseNotes1
def thr = Thread.currentThread();
def currentBuild = thr.executable;
def newParamAction = new hudson.model.ParametersAction(new hudson.model.StringParameterValue("JiraReleaseNotes2", JiraReleaseNotes1 ));
currentBuild.addAction(newParamAction);
Is scripted field appear on ISSUE EDIT or any transition screen?
For me, it appear on issue view screen only and unable to see on issue edit screen.
I want it to appear on EDIT screen as well as a readonly.
(have verified by just keeping - "free text template" and - return "some value").
Another:
When I have use below script on scripted field then it shows me error while execute:
Error message as below:
The indexer for this field expects a java.lang.String but
the script returned a com.atlassian.jira.issue.fields.CustomFieldImpl - this will cause problems.
Code:
import com.atlassian.jira.ComponentManager.
import com.atlassian.jira.issue.fields.CustomField
import com.atlassian.jira.issue.CustomFieldManager
CustomFieldManager customFieldManager = componentManager.getCustomFieldManager()
def componentManager = ComponentManager.getInstance()
def issueLinkManager = componentManager.getIssueLinkManager()
def selectedValues = customFieldManager.getCustomFieldObject("customfield_11447")
//custom field has multi selected values as it is a "multi select" field type.
return selectedValues
How I could use scripted field in issue edit/transition screen and also resolve above error.
For the first part of your question, no a scripted field wont be displayed on a Create, Edit or Transition screen. There is a work around for transition screens but I have not tried it https://gist.github.com/jechlin/5380119
Now the second part of your question. You are returning an object of CustomeField and you should be returning a String. What you want to do is
change this
def selectedValues = customFieldManager.getCustomFieldObject("customfield_11447")
to this
def cf = customFieldManager.getCustomFieldObject("customfield_11447")
def selectedValues = cf.getValue(issue)
Here is a link to the api documentation for JIRA (6.0.4):
https://developer.atlassian.com/static/javadoc/jira/6.0.4/reference/packages.html