gpt4 book ai didi

groovy - 如何在 Jenkins Workflow 中包含外部代码文件

转载 作者:行者123 更新时间:2023-12-04 00:38:01 24 4
gpt4 key购买 nike

我试图在我的工作流脚本中包含外部代码,但我遗漏了一些东西。第一步似乎奏效了。如果路径无效,则失败:

evaluate( new File('/home/larry.fast/Wkflo.groovy'))

但是我已经尝试了以下几种句法变化,但没有找到有效的咒语。所有尝试都产生了“无法解析类 mycode.Wkflo”的变体。
def z = mycode.Wkflo()

Wkflo.groovy 包含:
package mycode;
def hello() {
echo "Hello from workflow"
}

我也尝试过类似 run(File()) 或删除包声明的变体。

最佳答案

Jenkins 工作流文档现在包括一个关于“加载脚本文本”的部分
https://github.com/jenkinsci/workflow-plugin/blob/master/TUTORIAL.md但我发现很难跟上。这是一个简单的示例,演示了如何在外部文件中创建完整的工作流和其他方法。

Jenkins 中的工作流代码:

// Loading code requires a NODE context
// But we want the code accessible outside the node Context
// So declare extcode (object created by the LOAD operation) outside the Node block.
def extcode

node {
// paths are relative to your workspace
// you may need to run git to populate your workspace
git url: 'ssh://mygitrepo'
extcode = load 'myExtCode.wkflo'

// or you can directly access the file system
// Eg. when developing your code in a local git clone
extcode = load '/some/absolute/path/myExtCode.wkflo'

// extcode is now a groovy object containing everything declared in the file
extcode.hello('world')
}
// If your code contains Stage and Node blocks,
// you'll want to initiate that code outside of the node() block above
extcode.extMain()

------ myExtCode.wkflo
// Any command placed at the root of the file get executed during the load operation
echo "hello from loading myExtCode"

// Methods declared in external code are accessible
// directly from other code in the external file
// indirectly via the object created by the load operation
// eg. extcode.hello('use this syntax from your main code')
def hello(whom) {
echo "Hello ${whom}"
}

// Complete workflows should be created inside a controlling method
// else they will run nested inside the node() block when the load takes place (edit: added missing "def" keyword
def extMain() {
stage 'External Code is running'
node() {
hello('from external node block')
}
}

// !!Important Boilerplate!!
// The external code must return it's contents as an object
return this;

关于groovy - 如何在 Jenkins Workflow 中包含外部代码文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33712822/

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