如何在Jenkins Lockable Resource插件中获取锁定资源的名称

5

我正在使用Jenkins Lockable Resources插件决定在我的声明性流水线中用于各种构建操作的服务器。我已经按照下表所示设置了我的Lockable资源:

Resource Name       Labels

Win_Res_1           Windows
Win_Res_2           Windows
Win_Res_3           Windows
Lx_Res_1            Linux
Lx_Res_2            Linux
Lx_Res_3            Linux

我想锁定一个label,然后获取对应的锁定resource的名称。 我编写了以下代码,但无法获得所需的r值。
int num_resources = 1;
def label = "Windows"; /* I have hardcoded it here for simplicity. In actual code, I will get ${lable} from my code and its value can be either Windows or Linux. */

lock(label: "${label}", quantity: num_resources)
{
    def r = org.jenkins.plugins.lockableresources.LockableResourcesManager; /* I know this is incomplete but unable to get correct function call */
    println (" Locked resource r is : ${r} \n");

    /* r should be name of resource for example Win_Res_1. */
}
< p > Lockable Resources Plugin 的文档在这里可用:https://jenkins.io/doc/pipeline/steps/lockable-resources/https://plugins.jenkins.io/lockable-resources/

1个回答

7
您可以使用lock工作流步骤的variable参数来获取锁定资源的名称。此选项定义将存储锁定资源名称的环境变量的名称。请考虑以下示例。
pipeline {
    agent any

    stages {
        stage("Lock resource") {
            steps {
                script {
                    int num = 1
                    String label = "Windows"

                    lock(label: label, quantity: num, variable: "resource_name") {
                        echo "Locked resource name is ${env.resource_name}"
                    }
                }
            }
        }
    }
}

在这个例子中,锁定的资源名称可以使用env.resource_name变量访问。以下是管道运行的输出结果。
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Lock resource)
[Pipeline] script
[Pipeline] {
[Pipeline] lock
Trying to acquire lock on [Label: Windows, Quantity: 1]
Lock acquired on [Label: Windows, Quantity: 1]
[Pipeline] {
[Pipeline] echo
Locked resource name is Win_Res_1
[Pipeline] }
Lock released on resource [Label: Windows, Quantity: 1]
[Pipeline] // lock
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

你可以看到值Win_Res_1被赋给了env.resource_name变量。

1
谢谢@Szymon。这对我有用!!我不知道怎么忽略了variable: 'var'选项。 - Yash
嗨@Szymon,我遇到了一个问题,当我尝试锁定已被其他管道锁定的资源时,上面的代码返回错误“No such property: resource_name for class: groovy.lang.Binding”,并且打印消息显示“Locked resource name is null”。理想情况下,在这种情况下,管道应该等待资源(由其他管道锁定)变为空闲状态,然后获取它,而不是返回错误。如果所有资源都忙碌,我们需要添加其他内容来使脚本等待资源吗? - Yash

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接