Jenkins use import in Jenkinsfile - jenkins

How can I use import statements in Jenkinsfile?
This is the import statement:
import hudson.model.*
import jenkins.model.*
import hudson.tasks.test.AbstractTestResultAction
I want to use AbstractTestResultAction in a script section.

I solved it that way - this what the Jenkinsfile looks like:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import hudson.tasks.test.AbstractTestResultAction;
#NonCPS
def getTestSummary = { ->
def testResultAction = currentBuild.rawBuild.getAction(AbstractTestResultAction.class)
def summary = ""
if (testResultAction != null) {
def total = testResultAction.getTotalCount()
def failed = testResultAction.getFailCount()
def skipped = testResultAction.getSkipCount()
summary = "Test results:\n\t"
summary = summary + ("Passed: " + (total - failed - skipped))
summary = summary + (", Failed: " + failed + " ${testResultAction.failureDiffString}")
summary = summary + (", Skipped: " + skipped)
} else {
summary = "No tests found"
}
return summary
}
pipeline {
...
post {
always {
script {
def testSummaryRaw = getTestSummary()
def testSummary = "`${testSummaryRaw}`"
...
}
}
}
...
}

Related

How to change the Git URL in all Jenkins jobs

Does anyone have an updated version of ceilfors answer that works for both AbstractProject and WorkflowJob?
This is the solution I came up with. It was tested on Jenkins 2.355
The test was run from the script console.
For testing purposes, I limited the test to one Freestyle (AbstractProject) and one Pipeline (WorkflowJob) job each. You would need to modify the code below.
I hope others find this useful
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import hudson.plugins.git.*
import jenkins.*
import jenkins.model.*
def modifyGitUrl(url) {
def updatedUrl = url.toString().replace("git#gitlab", "git#github")
// println "updatedUrl = ${updatedUrl}"
return updatedUrl
}
Jenkins.instance.getAllItems(Job.class).each {
project = it.getFullName()
if(project.toString().equals("PL_Quick_Testing") || project.toString().equals("A_Freestyle_Job")) {
try {
if (it instanceof AbstractProject){
def oldScm = it.scm
def newUserRemoteConfigs = oldScm.userRemoteConfigs.collect {
new UserRemoteConfig(modifyGitUrl(it.url), it.name, it.refspec, it.credentialsId)
}
def newScm = new GitSCM(newUserRemoteConfigs, oldScm.branches, oldScm.doGenerateSubmoduleConfigurations,
oldScm.submoduleCfg, oldScm.browser, oldScm.gitTool, oldScm.extensions)
it.scm = newScm
it.save()
println "Done"
} else if (it instanceof WorkflowJob) {
def oldScm = it.getTypicalSCM()
def definition = it.getDefinition()
String scriptPath = it.getDefinition().getScriptPath()
def newUserRemoteConfigs = oldScm.userRemoteConfigs.collect {
new UserRemoteConfig(modifyGitUrl(oldScm.userRemoteConfigs.url[0]), it.name, it.refspec, it.credentialsId)
}
def newScm = new GitSCM(newUserRemoteConfigs, oldScm.branches, oldScm.doGenerateSubmoduleConfigurations,
oldScm.submoduleCfg, oldScm.browser, oldScm.gitTool, oldScm.extensions)
def newDefinition = new org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition(newScm, scriptPath)
it.definition = newDefinition
it.save()
println "Done"
} else {
println("${project} has no SCM")
}
} catch (Exception e) {
// e.printStackTrace()
}
}
}

Active choices reactive parameter doesn't show desired default branch

I want to use Jenkins' active choices reactive parameter to use Groovy script to show all branches in the repository.
I have the following code sample to get all branches of a repository and since that there are hundreds of branches, I want the default to be master branch.
Even though I specifically inserted the defaultBranch variable, it shows the first item as the default and not the branch I written to.
Code:
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import jenkins.model.Jenkins
def git_url ="url"
def getAllBranches(url, credentialID, activeChoice = false, defaultBranch = 'master') {
def jenkinsCredentials = CredentialsProvider.lookupCredentials(
com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey,
Jenkins.instance
);
def key = jenkinsCredentials.findResult { it.id == credentialID ? it.privateKey : null }
if( !key ) {
return 'Error: credentials not found'
}
Process process = ['ssh-agent','bash','-c', "echo '" + key + "' | ssh-add - 2> /dev/null && git ls-remote -t -h " + url].execute()
def out = new StringBuilder()
def err = new StringBuilder()
process.consumeProcessOutput( out, err )
process.waitFor()
if( err.size() > 0 ) return err
if( out.size() > 0 ) {
def branches = out.readLines().collect { it.split()[1].replaceAll('refs/heads/', '') }
if( activeChoice ) {
def defaultBranchIndex = branches.indexOf(defaultBranch)
if( defaultBranchIndex >= 0 ) branches.set(defaultBranchIndex, defaultBranch + ':selected')
}
return branches
}
}
return getAllBranches(git_url, "efa7bed9-56a0-42ac-8fa3-a68fe7700801")
You have set default for activeChoice to false in the getAllBranches method and do not set while calling it, thus the if-branch that adds the :selected is never entered.
I changed activeChoice method's value from false to true and it solved my issue:
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import jenkins.model.Jenkins
def git_url ="url"
def getAllBranches(url, credentialID, activeChoice = true, defaultBranch = 'master') {
def jenkinsCredentials = CredentialsProvider.lookupCredentials(
com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey,
Jenkins.instance
);
def key = jenkinsCredentials.findResult { it.id == credentialID ? it.privateKey : null }
if( !key ) {
return 'Error: credentials not found'
}
Process process = ['ssh-agent','bash','-c', "echo '" + key + "' | ssh-add - 2> /dev/null && git ls-remote -t -h " + url].execute()
def out = new StringBuilder()
def err = new StringBuilder()
process.consumeProcessOutput( out, err )
process.waitFor()
if( err.size() > 0 ) return err
if( out.size() > 0 ) {
def branches = out.readLines().collect { it.split()[1].replaceAll('refs/heads/', '') }
if( activeChoice ) {
def defaultBranchIndex = branches.indexOf(defaultBranch)
if( defaultBranchIndex >= 0 ) branches.set(defaultBranchIndex, defaultBranch + ':selected')
}
return branches
}
}
return getAllBranches(git_url, "efa7bed9-56a0-42ac-8fa3-a68fe7700801")

Jenkins: View last X builds

I want to view the more recent X builds for several Jenkins jobs.
So if I wanted to show the last 5 builds for jobs 1-5 it would looks something like this:
status build time
-------------------------
pass job1#3 13:54
fail job1#2 13:05
fail job1#1 13:01
pass job5#1 12:17
pass job3#1 11:03
How can I accomplish this?
Notice the builds of the jobs are woven together so if one job has run many builds recently it will show up more than other jobs that haven't run as much.
Executing the following script in the Script Console (Manage Jenkins -> Script Console):
import java.text.SimpleDateFormat
def numHoursBack = 24
def dateFormat = new SimpleDateFormat("HH:mm")
def buildNameWidth = 30
def cutOfTime = System.currentTimeMillis() - numHoursBack * 3600 * 1000
SortedMap res = new TreeMap();
for (job in Jenkins.instance.getAllItems(BuildableItem.class)) {
for (build in job.getBuilds()) {
if (build.getTimeInMillis() < cutOfTime) {
break;
}
res.put(build.getTimeInMillis(), build)
}
}
def format = "%-10s%-${buildNameWidth}s%-10s"
println(String.format(format, "status", "build", "Time"))
for (entry in res.descendingMap().entrySet()) {
def build = entry.getValue()
println(String.format(format, build.getResult(), build.getFullDisplayName(), dateFormat.format(build.getTime())))
}
For me this gives:
status build Time
SUCCESS xxx #107393 17:53
SUCCESS xxx #107392 17:48
SUCCESS xxx #107391 17:43
null yyy #3030 17:38
SUCCESS xxx #107390 17:38
FAILURE zzz #3248 17:37
...
You might need to change the numHoursBack constant, it controls the number of hours back to look for builds. As well as the buildNameWidth which determines the column width of the build column (if you have really long job and build names you might need to extend this).
Here is a bit cleanup version of Jon S Groovy script. Also displaying worst build information.
import hudson.model.*;
import java.text.SimpleDateFormat;
//
// Settings
//
def numHoursBack = 24;
def dateFormat = new SimpleDateFormat("HH:mm");
def cutOfTime = System.currentTimeMillis() - numHoursBack * 3600 * 1000;
/**
* Basic build information.
*/
def printBuildInfo(finalizedBuild) {
String level = "INFO";
String result = finalizedBuild.getResult().toString();
switch (result) {
case "UNSTABLE":
level = "WARNING";
break;
case "FAILURE":
level = "ERROR";
break;
}
// basic info and URL
println(String.format(
"[%s] Build %s result is: %s.",
level,
finalizedBuild.getFullDisplayName(),
result
));
// pipe description from downstream
def description = finalizedBuild.getDescription();
if (description != null && !description.isEmpty()) {
println(description.replaceAll("<br>", ""));
}
return finalizedBuild;
}
/**
* Get recent build items.
*/
def getRencentBuilds(cutOfTime) {
SortedMap res = new TreeMap();
for (job in Jenkins.instance.getAllItems(BuildableItem.class)) {
for (build in job.getBuilds()) {
if (build.getTimeInMillis() < cutOfTime) {
break;
}
res.put(build.getTimeInMillis(), build);
}
}
return res;
}
/**
* Print build items.
*
* minResult - minimum to print
*/
def printBuilds(builds, minResult, dateFormat) {
def format = "%-10s %-8s %s";
Result worstResult = Result.SUCCESS;
def worstBuild = null;
// header
println(String.format(format, "status", "Time", "build"));
// list
for (entry in builds.descendingMap().entrySet()) {
def build = entry.getValue();
Result result = build.getResult();
if (result.isWorseThan(worstResult)) {
worstResult = result;
worstBuild = build;
}
if (result.isWorseOrEqualTo(minResult)) {
println(String.format(
format, build.getResult(), dateFormat.format(build.getTime()), build.getFullDisplayName()
));
}
}
return worstBuild;
}
def builds = getRencentBuilds(cutOfTime);
println ("\n\n----------------------\n Failed builds:\n");
def worstBuild = printBuilds(builds, Result.FAILURE, dateFormat);
println ("\n\n----------------------\n Worst build:\n");
if (worstBuild != null) {
printBuildInfo(worstBuild);
}
println ("\n\n----------------------\n All builds:\n");
printBuilds(builds, Result.SUCCESS, dateFormat);

Jenkins RoleBasedAuthorizationStrategy add user to Role Groovy Script

I am trying to find a groovy script to add an existing user to a Role using RoleBasedAuthorizationStrategy. Any help would be greatly appreciated.
I ran into the same need. After doing some web searching and looking at the plugin's code from GitHub, I found one link that provided some insight: https://issues.jenkins-ci.org/browse/JENKINS-23709. Based on that I hacked together a quick Groovy script that assigns a specific user to a specific role. Been awhile since I've done Groovy, so pardon the dust. Feel free to use this as an example for your own needs.
import jenkins.model.*
import hudson.security.*
import java.util.*
import com.michelin.cio.hudson.plugins.rolestrategy.*
import java.lang.reflect.*
def roleName = "guest"
def userName = "bot-release"
def findGuestRoleEntry(grantedRoles, roleName)
{
for (def entry : grantedRoles)
{
Role role = entry.getKey()
if (role.getName().equals(roleName))
{
return entry
}
}
return null
}
def authStrategy = Jenkins.instance.getAuthorizationStrategy()
if(authStrategy instanceof RoleBasedAuthorizationStrategy){
RoleBasedAuthorizationStrategy roleAuthStrategy = (RoleBasedAuthorizationStrategy) authStrategy
// Make constructors available
Constructor[] constrs = Role.class.getConstructors();
for (Constructor<?> c : constrs) {
c.setAccessible(true);
}
// Make the method assignRole accessible
Method assignRoleMethod = RoleBasedAuthorizationStrategy.class.getDeclaredMethod("assignRole", String.class, Role.class, String.class);
assignRoleMethod.setAccessible(true);
def grantedRoles = authStrategy.getGrantedRoles(RoleBasedAuthorizationStrategy.GLOBAL);
if (grantedRoles != null)
{
// println "Got grantedRoles for " + RoleBasedAuthorizationStrategy.GLOBAL
def roleEntry = findGuestRoleEntry(grantedRoles, roleName);
if (roleEntry != null)
{
// println "Found role " + roleName
def sidList = roleEntry.getValue()
if (sidList.contains(userName))
{
println "User " + userName + " already assigned to role " + roleName
} else {
println "Adding user " + userName + " to role " + roleName
roleAuthStrategy.assignRole(RoleBasedAuthorizationStrategy.GLOBAL, roleEntry.getKey(), userName);
println "OK"
}
Jenkins.instance.save()
} else {
println "Unable to find role " + roleName
}
} else {
println "Unable to find grantedRoles for " + RoleBasedAuthorizationStrategy.GLOBAL
}
} else {
println "Role Strategy Plugin not found!"
}

jenkins cli with checkout Subversion using groovy script

Is there a way to check out any Subversion project using Jenkins-Cli by executing a groovy script on the master? I can get to the point of creating SVN client manager[org.tmatesoft.svn.core.wc.SVNClientManager], but can't really understand how to employ that in checking out an SVN project from the URL.
After a lot of hit and trials I have come up with this, might be useful for someone else:
import jenkins.*;
import jenkins.model.*;
import hudson.*;
import hudson.model.*;
import hudson.slaves.SlaveComputer;
import hudson.scm.SubversionSCM;
import hudson.remoting.Channel;
import hudson.FilePath;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationProvider;
import org.tmatesoft.svn.core.wc.SVNLogClient;
import org.tmatesoft.svn.core.SVNDirEntry;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNDirEntry;
import org.tmatesoft.svn.core.ISVNDirEntryHandler;
import org.tmatesoft.svn.core.wc.SVNUpdateClient;
import java.lang.*;
import java.util.ArrayList;
import java.util.List;
private boolean checkNodeExist(String node_Name){
if (Jenkins.getInstance().slaves.find({it.name == node_Name}) == null)
return false;
else
return true;
}
private ISVNAuthenticationProvider createAuthenticationProvider(AbstractProject context) {
return Jenkins.getInstance().getDescriptorByType(SubversionSCM.DescriptorImpl.class)
.createAuthenticationProvider(context);
}
public class SimpleSVNDirEntryHandler implements ISVNDirEntryHandler {
private final List<SVNDirEntry> dirs = new ArrayList<SVNDirEntry>();
public List<String> getDirs() {
List<String> sortedDirs = new ArrayList<String>();
for (SVNDirEntry dirEntry : dirs) {
sortedDirs.add(dirEntry.getName());
}
return sortedDirs;
}
public void handleDirEntry(SVNDirEntry dirEntry) throws SVNException {
dirs.add(dirEntry);
}
}
public void PerfromSVNListOperationOnMaster(SVNURL svnUrl){
try{
SVNRepository repo = SVNRepositoryFactory.create(svnUrl);
SVNClientManager clientManager = SubversionSCM.createSvnClientManager(createAuthenticationProvider())
SVNLogClient logClient = clientManager.getLogClient();
SimpleSVNDirEntryHandler dirEntryHandler = new SimpleSVNDirEntryHandler();
List<String> dirs = new ArrayList<String>();
logClient.doList(repo.getLocation(),SVNRevision.HEAD, SVNRevision.HEAD,false,SVNDepth.INFINITY,SVNDirEntry.DIRENT_KIND,dirEntryHandler)
dirs = dirEntryHandler.getDirs();
println (dirs)
}
catch(SVNException svnEx){
println "#Error: " + svnEx;
throw svnEx
}
}
public void PerfromSVNCheckOutOperation(SVNURL svnUrl,boolean isMaster,String appender,SlaveComputer computer = null){
try{
SVNRepository repo = SVNRepositoryFactory.create(svnUrl);
SVNClientManager clientManager = SubversionSCM.createSvnClientManager(createAuthenticationProvider());
SVNUpdateClient updateClient = clientManager.getUpdateClient();
updateClient.setIgnoreExternals(false);
String destDir = svnUrl.getPath().substring(svnUrl.getPath().lastIndexOf('/')+1);
if (isMaster == true){
updateClient.doCheckout(repo.getLocation(),new java.io.File(System.getProperty("java.io.tmpdir"),destDir + '_' + appender),SVNRevision.HEAD,SVNRevision.HEAD,SVNDepth.INFINITY,false);
}else{
if (computer == null){
throw new IllegalArgumentException("#Error: Argument:computer can't be null when we need to checkout in slave");
}else{
updateClient.doCheckout(repo.getLocation(),new java.io.File(System.getProperty("java.io.tmpdir"),destDir + '_' + appender),SVNRevision.HEAD,SVNRevision.HEAD,SVNDepth.INFINITY,false);
Channel slaveChannel = computer.getChannel();
FilePath fpSrc = new hudson.FilePath(new java.io.File(System.getProperty("java.io.tmpdir"),destDir + '_' + appender));
//println new java.io.File((slave.getWorkspaceRoot().toString()),destDir).toString().replace('\\','/')
FilePath fpDestination = new hudson.FilePath(slaveChannel,new java.io.File((slave.getWorkspaceRoot().toString()),destDir + '_' + appender).toString().replace('\\','/'));
println "Copying files recursively from Temp directory in master to slave";
int files_copied = fpSrc.copyRecursiveTo(fpDestination);
println files_copied
fpSrc.deleteRecursive();
}
}
}
catch (Exception ex){
throw new Exception("#Error:",ex);
}
}
if (args.length == 4){
String url = new String(args[0]);
SVNURL svn_url = null;
try{
svn_url = SVNURL.parseURIDecoded(url);
}
catch(SVNException svnEX){
println "#Error: Check SVN repository Location.";
throw svnEX;
}
String nodeName = new String(args[1]);
String operation = new String(args[2]);
String checkoutAppendString = new String(args[3]);
println args
if (nodeName.equalsIgnoreCase("master")){
println "Executing script on master"
if (operation.equalsIgnoreCase("list")){
PerfromSVNListOperationOnMaster(svn_url);
}else{
PerfromSVNCheckOutOperation(svn_url,true,checkoutAppendString);
}
}else{
if (checkNodeExist(nodeName)){
slave = Jenkins.getInstance().slaves.find({it.name == nodeName});
SlaveComputer computer = slave.getComputer();
if (computer.isOffline()){
println "#Error: $slave is offline."
return
}else{
if (operation.equalsIgnoreCase("list")){
PerfromSVNListOperationOnMaster(svn_url)
}else{
PerfromSVNCheckOutOperation(svn_url,false,checkoutAppendString,computer);
}
}
}else{
println "#Error: $nodeName not found."
return
}
}
}else{
println "Invalid Usage, expecting 3 arguments : 1.RepositoryURL 2.NodeName 3.OperationType"
return
}

Resources