How to Reference A Jenkins Global Shared Library - jenkins

After reviewing the docs, a number of questions here on SO, and trying a dozen or so different script configurations, I cannot figure out how to reference a shared Groovy library. I've added the library like so:
This appears to be working. I'm referencing the script like so:
You can see the error message therein:
Script1: 1: unable to resolve class Library , unable to find class
for annotation # line 1, column 1. #Library('sonarQubeAPI')_
The script code, not I think it matters, looks like this:
import groovy.json.JsonSlurper
class SonarQubeAPI{
static string getVersion(){
return "1.0";
}
static void getSonarStatus(projectKey){
def sonarQubeUserToken = "USERTOKEN";
def projectStatusUrl = "pathtosonarqube/api/qualitygates/project_status?projectKey=" + projectKey;
println("Retrieving project status for " + projectKey);
def json = getJson(sonarQubeUserToken, projectStatusUrl);
def jsonSlurper = new JsonSlurper();
def object = jsonSlurper.parseText(json);
println(object.projectStatus.status);
}
static string getJson(userToken, url){
def authString = "${userToken}:".getBytes().encodeBase64().toString();
def conn = url.toURL().openConnection();
conn.setRequestProperty( "Authorization", "Basic ${authString}" );
return conn.content.text;
}
}
I'm probably just a magic character off, but I can't seem to lock it down.

Shared libraries are a feature of Jenkins Pipelines, not of Jenkins (core) itself. You can use them only in Pipeline jobs (and child types like Multibranch Pipeline).

Related

Is it possible to use build user vars plugin in a Jenkins shared library?

I'm implementing functionality to expose the triggering user for a Jenkins pipeline to our CD system, so I've grabbed the build user vars plugin: https://plugins.jenkins.io/build-user-vars-plugin/
The way the plugin seems to work is that you wrap the code you need the variables exposed to, like so:
wrap([$class: 'BuildUser']) {
userId = env.BUILD_USER_ID
}
I tried this on a general pipeline and just echoed it out, all was well.
I then tried implementing it in our shared library so that this would happen on all calls to CD, and I'm hitting an error.
wrap([$class: 'BuildUser']) {
jobBuildUrl ="${jobBuildUrl}&USER_ID=${env.BUILD_USER_ID}"
}
[2021-08-19T10:20:22.852Z] hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: com.company.jenkins.pipelines.BuildManager.wrap() is applicable for argument types: (java.util.LinkedHashMap, org.jenkinsci.plugins.workflow.cps.CpsClosure2) values: [[$class:BuildUser], org.jenkinsci.plugins.workflow.cps.CpsClosure2#1c9a210c]
Is there any way to use this plugin code within a shared library? If so how?
I'm lead to believe not, but I thought it was worth the asking. For reference, there is this outstanding issue: https://issues.jenkins.io/browse/JENKINS-44741
Side note, I'm trying to do this without touching everybody's pipelines themselves. If this is impossible with this plugin, I'll probably just implement my own version of it within the shared lib.
That plugin is hard to use and has many issues, one of them is with shared libraries.
Instead just implement it by yourself, it is relatively easy and allows you much more control over the logic of what is done, error handling and which parameters you return.
You can use something like the following:
/**
* Get the last upstream build that triggered the current build
* #return Build object (org.jenkinsci.plugins.workflow.job.WorkflowRun) representing the upstream build
*/
#NonCPS
def getUpstreamBuild() {
def build = currentBuild.rawBuild
def upstreamCause
while (upstreamCause = build.getCause(hudson.model.Cause$UpstreamCause)) {
build = upstreamCause.upstreamRun
}
return build
}
/**
* Get the properties of the build Cause (the event that triggered the build)
* #param upstream If true (Default) return the cause properties of the last upstream job (If the build was triggered by another job or by a chain of jobs)
* #return Map representing the properties of the user that triggered the current build.
* Contains keys: USER_NAME, USER_ID
*/
#NonCPS
def getUserCauseProperties(Boolean upstream = true) {
def build = upstream ? getUpstreamBuild() : currentBuild.rawBuild
def cause = build.getCause(hudson.model.Cause$UserIdCause)
if (cause) {
return ['USER_NAME': cause.userName, 'USER_ID': cause.userId]
}
println "Job was not started by a user, it was ${build.getCauses()[0].shortDescription}"
return [:]
}
I was also not able to use wrap([$class: 'BuildUser']) into groovy method. Therefore I think I found alternative way which seems to do the trick. You may get the username and userid (which might return email, depends on your setup) by just the following:
def build = currentBuild.rawBuild
def cause = build.getCause(hudson.model.Cause.UserIdCause.class)
def userName = cause.getUserName() // or use getUserId()

Not that kind of Map exception with Jenkins and Groovy

I have a string in groovy that I want to convert into a map. When I run the code on my local computer through a groovy script for testing, I have no issues and a lazy map is returned. I can then convert that to a regular map and life goes on. When I try the same code through my Jenkins DSL pipeline, I run into the exception
groovy.json.internal.Exceptions$JsonInternalException: Not that kind of map
Here is the code chunk in question:
import groovy.json.*
String string1 = "{value1={blue green=true, red pink=true, gold silver=true}, value2={red gold=false}, value3={silver brown=false}}"
def stringToMapConverter(String stringToBeConverted){
formattedString = stringToBeConverted.replace("=", ":")
def jsonSlurper = new JsonSlurper().setType(JsonParserType.LAX)
def mapOfString = jsonSlurper.parseText(formattedString)
return mapOfString
}
def returnedValue = stringToMapConverter(string1)
println(returnedValue)
returned value:
[value2:[red gold:false], value1:[red pink:true, gold silver:true, blue green:true], value3:[silver brown:false]]
I know that Jenkins and Groovy differ in various ways, but from searches online others suggest that I should be able to use the LAX JsonSlurper library within my groovy pipeline. I am trying to avoid hand rolling my own string to map converter and would prefer to use a library if it's out there. What could be the difference here that would cause this behavior?
Try to use
import groovy.json.*
//#NonCPS
def parseJson(jsonString) {
// Would like to use readJSON step, but it requires a context, even for parsing just text.
def lazyMap = new JsonSlurper().setType(JsonParserType.LAX).parseText(jsonString.replace("=", ":").normalize())
// JsonSlurper returns a non-serializable LazyMap, so copy it into a regular map before returning
def m = [:]
m.putAll(lazyMap)
return m
}
String string1 = "{value1={blue green=true, red pink=true, gold silver=true}, value2={red gold=false}, value3={silver brown=false}}"
def returnedValue = parseJson(string1)
println(returnedValue)
println(JsonOutput.toJson(returnedValue))
You can find information about normalize here.

Groovy Missing Property Exception

I have a jenkins build that needs to get the filenames for all files checked in within a changeset.
I have installed groovy on the slave computer and configured Jenkins to use it. I am running the below script that should return the names (or so I assume as this may be wrong as well) and print to the console screen however I am getting this error:
groovy.lang.MissingPropertyException: No such property: paths for class: hudson.plugins.tfs.model.ChangeSet
Here is the Groovy System Script:
import hudson.plugins.tfs.model.ChangeSet
// work with current build
def build = Thread.currentThread()?.executable
// get ChangesSets with all changed items
def changeSet= build.getChangeSet()
def items = changeSet.getItems()
def affectedFiles = items.collect { it.paths }
// get file names
def fileNames = affectedFiles.flatten().findResults
fileNames.each {
println "Item: $it" // `it` is an implicit parameter corresponding to the current element
}
I am very new to Groovy and Jenkins so if its syntax issue or if I'm missing a step please let me know.
I don't know the version of jenkins you are using but according to the sourcecode of ChangeSet that you can find here I suggest you to replace line 9 with:
def affectedFiles = items.collect { it.getAffectedPaths() }
// or with the equivalent more groovy-idiomatic version
def affectedFiles = items.collect { it.affectedPaths }
Feel free to comment the answer if there will be more issues.

Jenkins: Configure ActiveDirectorySecurityRealm Plugin using Groovy

I'm currently spending some time setting up a generic configuration using Jenkins AD-SecurityRealm (ActiveDirectorySecurityRealm) Plugin (v2.6) and stuck over a nasty issue: It seems that my approach to (auto) set up a valid AD-connection (following the corresponding documentation) is not working at all. Every time I'll re-init my Jenkins instance an incomplete config.xml will provide - the "bindName" property (XML-node) is always missing. This property is required by the ad-server I'll use and so I've to override the config manually to solve this issue.
I haven't the vaguest idea why this still happens.
my groovy code (excerpt)
String _domain = 'my-primary-ad-server-running.acme.org'
String _site = 'jenkins.acme.org'
String _bindName = 'ad-bind-user'
String _bindPassword = 'ad-bind-password-super-secret-123'
String _server = 'my-primary-ad-server-running.acme.org'
def hudsonActiveDirectoryRealm = new ActiveDirectorySecurityRealm(_domain, _site, _bindName, _bindPassword, _server)
def instance = Jenkins.getInstance()
instance.setSecurityRealm(hudsonActiveDirectoryRealm)
instance.save()
my config.xml result (excerpt)
<securityRealm class="hudson.plugins.active_directory.ActiveDirectorySecurityRealm" plugin="active-directory#2.6">
<domains>
<hudson.plugins.active__directory.ActiveDirectoryDomain>
<name>my-primary-ad-server-running.acme.org</name>
<servers>my-primary-ad-server-running.acme.org:3268</servers>
<bindPassword>{###-fancy-crypted-super-password-nobody-can-decrypt-anymore-###}</bindPassword>
</hudson.plugins.active__directory.ActiveDirectoryDomain>
</domains>
<startTls>true</startTls>
<groupLookupStrategy>AUTO</groupLookupStrategy>
<removeIrrelevantGroups>false</removeIrrelevantGroups>
<tlsConfiguration>TRUST_ALL_CERTIFICATES</tlsConfiguration>
</securityRealm>
my config.xml required (excerpt)
<securityRealm class="hudson.plugins.active_directory.ActiveDirectorySecurityRealm" plugin="active-directory#2.6">
<domains>
<hudson.plugins.active__directory.ActiveDirectoryDomain>
<name>my-primary-ad-server-running.acme.org</name>
<servers>my-primary-ad-server-running.acme.org:3268</servers>
<bindName>ad-bind-user</bindName>
<bindPassword>{###-fancy-crypted-super-password-nobody-can-decrypt-anymore-###}</bindPassword>
</hudson.plugins.active__directory.ActiveDirectoryDomain>
</domains>
<startTls>true</startTls>
<groupLookupStrategy>AUTO</groupLookupStrategy>
<removeIrrelevantGroups>false</removeIrrelevantGroups>
<tlsConfiguration>TRUST_ALL_CERTIFICATES</tlsConfiguration>
</securityRealm>
Thanks #kosta.
Following script also works using active-directory 2.10 and jenkins 2.150.1
This also include site information.
import hudson.plugins.active_directory.ActiveDirectoryDomain
import hudson.plugins.active_directory.ActiveDirectorySecurityRealm
import hudson.plugins.active_directory.GroupLookupStrategy
String _domain = 'dev.test.com'
String _site = 'HQ'
String _bindName = 'dev\jenkins'
String _bindPassword = 'test'
String _server = 'dev.test.com:2328'
def hudsonActiveDirectoryRealm = new ActiveDirectorySecurityRealm(_domain, _site, _bindName, _bindPassword, _server)
hudsonActiveDirectoryRealm.getDomains().each({
it.bindName = hudsonActiveDirectoryRealm.bindName
it.bindPassword = hudsonActiveDirectoryRealm.bindPassword
it.site = hudsonActiveDirectoryRealm.site
})
def instance = Jenkins.getInstance()
instance.setSecurityRealm(hudsonActiveDirectoryRealm)
instance.save()
Check this screenshot: Configure Global Security
If you look at the source code for ActiveDirectorySecurityRealm you will see that the bindName is marked as transient, thus it won't be persisted as part of the config XML.
The only solution to get the desired config.xml is to force the config.xml by providing a custom static one and not use the init script.
I was able to solve this issue by adding the following code at the end (Tested on 2.6 and 2.8). You also need to make sure that your credentials are valid because the plugin is doing an initial connectivity check https://issues.jenkins-ci.org/browse/JENKINS-48513
hudsonActiveDirectoryRealm.getDomains().each({
it.bindName = hudsonActiveDirectoryRealm.bindName
it.bindPassword = hudsonActiveDirectoryRealm.bindPassword
})
instance.setSecurityRealm(hudsonActiveDirectoryRealm)
instance.save()

Groovy Script save domain class

I created the following script in the script folder using netbeans. I can't save the domain class. Also, if I deploy the entire project as a war file, can I run the script using Windows scheduler?
Script
def json = ""
def txt = new URL("http://free.worldweatheronline.com/feed/weather.ashx?q=Singapore,Singapore&format=xml&num_of_days=1&key=b674fb7e94131612112609").text
def records = new XmlSlurper().parseText(txt)
def weather = records.weather
def dates = weather.date
def min = weather.tempMinC
def max = weather.tempMaxC
def img = weather.weatherIconUrl
def desc = weather.weatherDesc
def descLink = desc.toString().replaceAll(" ","%20")
println max
Weathers w = new Weathers()
w.cityName="singapore"
w.day = dates
w.description =desc
w.max = max
w.img = img
w.min = min
w.url = "jk"
Domain class
package org.mPest
class Weathers {
int id
String day
String min
String max
String img
String description
String cityName
String url
static constraints = {
id(blank:false, unique:true)
cityName(blank:false)
url(blank:false)
}
}
You can't use domain classes directly.
See this FAQ to read how to use domain classes from src/groovy:
import org.codehaus.groovy.grails.commons.ApplicationHolder
//…
def book = ApplicationHolder.application.getClassForName("library.Book").findByTitle("Groovy in Action")
I don't know if it possible to run the war packed script from windows but you could use the grails Quartz plugin to schedule your task...
Take a look at the grails run-script command. You should be able to use that to execute a script using something like windows scheduler or cron, but you'd have to have the full source code (not the war file) available for the script to execute with.
In Grails 2.x you should use Holders instead of ApplicationHolder. For example:
import grails.util.Holders
def validKeys = Holders.grailsApplication.getClassForName("com.vcd.Metadata").findAll { it.metadataKey }*.metadataKey

Resources