gpt4 book ai didi

jenkins - 如何在 Jenkinsfile 中进行字符串到整数的转换?

转载 作者:行者123 更新时间:2023-12-04 21:06:50 37 4
gpt4 key购买 nike

我的 Jenkinsfile 中有以下内容:

pipeline {
agent none
environment {
timeout_mins = 1
}
options {
timeout(time: "${env.timeout_mins}", unit: 'MINUTES')
}
stages {
stage("test print") {
steps {
echo "timeout_mins: ${env.timeout_mins}"
sh "sleep 120"
}
}
}
}
我想在多个地方重复使用诸如 timeout_mins 之类的环境参数,但需要在某些插件的某些地方将其转换为整数。我在上面的例子中得到的错误如下:
Processing environment for org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty
java.lang.IllegalArgumentException: Could not instantiate {time=null, unit=MINUTES} for TimeoutStep(time: int, unit?: TimeUnit[NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS]): java.lang.ClassCastException: org.jenkinsci.plugins.workflow.steps.TimeoutStep.time expects int but received class java.lang.String
at org.jenkinsci.plugins.structs.describable.DescribableModel.instantiate(DescribableModel.java:264)
at org.jenkinsci.plugins.workflow.steps.StepDescriptor.newInstance(StepDescriptor.java:194)
at org.jenkinsci.plugins.workflow.cps.DSL.invokeStep(DSL.java:181)
at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:126)
at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:108)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:48)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.methodCall(DefaultInvoker.java:18)
at
有没有人有办法在 Jenkinsfile 中将 String 转换为 int?
我试过 time: env.timeout_mins ,但这会产生一个空值。 time: ${env.timeout_mins} ,产生:
WorkflowScript:7:方法调用参数@第 7 行,第 23 列。
超时(时间:${env.timeout_mins},单位:'分钟') time: ${env.timeout_mins}.toInteger() ,同上 time: ${env.timeout_mins.toInteger()} ,同上
还有什么我可以尝试的吗?

最佳答案

这不是失败的转换,只是您无法在选项块中引用环境变量。

这也失败(空指针异常):

pipeline {
agent none
environment {
timeout_mins = 'MINUTES'
}
options {
timeout(time: 1, unit: env.timeout_mins)
}
stages {
stage("test print") {
steps {
echo "timeout_mins: ${env.timeout_mins}"
sh "sleep 120"
}
}
}
}

这有效:
def timeout_in_minutes = 1

pipeline {
agent none
options {
timeout(time: timeout_in_minutes, unit: 'MINUTES')
}
stages {
stage("test print") {
steps {
echo "timeout_in_minutes: ${env.timeout_in_minutes}"
sh "sleep 120"
}
}
}
}

关于jenkins - 如何在 Jenkinsfile 中进行字符串到整数的转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43623111/

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