首页 > 解决方案 > Jenkins pipeline Lockable Resources 插件:如何根据定义的标签锁定特定资源

问题描述

我有以下使用特定标签定义的资源。

Resource:Windows1
Labels:win10,64bit,firefox
Resource:Windows2
Labels:win10,32bit,chrome
Resource:Linux1
Labels:opensuse15.1,32bit,chrome
Resource:Linux2
Labels:opensuse15.1,64bit,chrome
Resource:Linux3
Labels:centos7,64bit,firefox

并在 Jenkins 项目中创建了以下管道:

import org.jenkins.plugins.lockableresources.LockableResourcesManager as manager
    pipeline {
        agent none
        stages {
            stage('Build') {
                agent none
                steps {
                    script {      
                      def myResources = manager.get().getResources()
                      def String myLabels = manager.get().getAllLabels()
                      def notLocked = myResources.find{rName-> 
                         manager.get().fromName(rName).with{ r-> !r.isLocked() && !r.isQueued() && myLabels.contains("opensuse15.1") && myLabels.contains("chrome") && myLabels.contains("64bit")}
                                   }  
                      if(notLocked){
                         lock(notLocked){         
                                    }
                               }
                    
                    }
                }
            
            }
        }
    }

尝试根据特定标签选择资源时出现此错误:

hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: org.jenkins.plugins.lockableresources.LockableResourcesManager.fromName() is applicable for argument types: (org.jenkins.plugins.lockableresources.LockableResource) values: [Windows1]
Possible solutions: fromName(java.lang.String)
            at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:58)
...

有没有人遇到过类似的情况,可以帮帮我吗?

标签: jenkins-pipeline

解决方案


对我有用的代码是:

pipeline {
    agent none
    stages {
        stage('Build') {
            agent none
            steps {
                script {
                    def OS = "win10" 
                    def bit = "64bit"
                    def browser = ""
                    def manager = org.jenkins.plugins.lockableresources.LockableResourcesManager
                    def myResources = manager.get().resources
                    def myLabels = manager.get().allLabels
                    def checkLocked = myResources.find { r -> 
                            !r.isLocked() && !r.isQueued() && r.labels.contains(OS) && r.labels.contains(bit) && r.labels.contains(browser)}
                    if(checkLocked){
                        def myResource = checkLocked.toString()
                        lock(myResource){
                        println "Resource was succesfully locked"   
                        sleep 30
                                 }
                            } else {
                            println "Sorry!!! No resource is available in this moment"    
                            }

                }
            }
        
        }
    }
}

推荐阅读