Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Helper pipeline library for label based locking in jenkins pipeline
// vim: noet sw=4 ts=4 cindent
// This is a helper that runs as privileged code, to get the LockableResource to pipeline jobs
package PipelineHelpers;
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted
// Wrapper class to expose a safe subset to the client code
class LockableResourcesHelper implements Serializable {
static class LockableResourceHelper implements Serializable {
private String resource_name
private String resource_description
private String resource_labels
public LockableResourceHelper(String name, String description, String labels) {
resource_name = name
resource_description = description
resource_labels = labels
String getName() {
return resource_name
String getDescription() {
return resource_description
String getLabels() {
return resource_labels
public static lockAndGetLockableResources(currentBuild) {
// Call this one to lock and get the resources reserved by
// org.jenkins.plugins.lockableresources.RequiredResourcesProperty
// IE job-dsl: wrappers { lockableResources { .. } }
def LRM = org.jenkins.plugins.lockableresources.LockableResourcesManager.class.get()
def required = LRM.getResourcesFromProject(currentBuild.getFullProjectName())
if (required.isEmpty())
throw AbortException("getResourcesFromProject didn't return any resources! Have you lost the org.jenkins.plugins.lockableresources.RequiredResourcesProperty property block?")
if (LRM.lock(required, currentBuild.getRawBuild(), null)) {
//echo currentBuild.getFullProjectName() + " acquired lock on " + required
return getLockableResources(currentBuild)
} else {
throw AbortException(currentBuild.getFullProjectName() + " failed to lock " + required)
public static getLockableResources(currentBuild) {
// Call this one to get the resources that a lock() step locked for you
// IE pipeline: lock() {}
def builds_resources = org.jenkins.plugins.lockableresources.LockableResourcesManager.class.get().getResourcesFromBuild(currentBuild.getRawBuild())
def helper_resources = []
for (resource in builds_resources) {
helper_resources += new LockableResourceHelper(resource.getName(), resource.getDescription(), resource.getLabels())
return helper_resources
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment