gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:57:59 25 4
gpt4 key购买 nike

我正在使用 Jenkins Lockable Resources 插件来决定将哪个服务器用于声明性管道中的各种构建操作。我已经设置了我的可锁定资源,如下表所示:

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. */
}
Lockable Resources Plugin 的文档可在此处获得: https://jenkins.io/doc/pipeline/steps/lockable-resources/

https://plugins.jenkins.io/lockable-resources/

最佳答案

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

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 变量。

关于groovy - 如何在Jenkins Lockable Resource插件中获取锁定资源的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61115066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com