[英]How to call a groovy function from a Jenkinsfile?
Despite following this answer and others, I am unable to successfully use a local groovy file in my Jenkinsfile (both are in the same repository).尽管遵循了这个答案和其他答案,但我无法在我的 Jenkinsfile 中成功使用本地 groovy 文件(两者都在同一个存储库中)。
def deployer = null
...
...
...
pipeline {
agent {
label 'cf_slave'
}
options {
skipDefaultCheckout()
disableConcurrentBuilds()
}
stages {
stage ("Checkout SCM") {
steps {
checkout scm
}
}
...
...
...
stage ("Publish CF app") {
steps {
script {
STAGE_NAME = "Publish CF app"
deployer = fileLoader.load ('deployer')
withCredentials(...) {
if (BRANCH_NAME == "develop") {
...
...
...
} else {
deployer.generateManifest()
}
}
}
}
}
...
...
}
deployer.groovy : deployer.groovy :
#!/usr/bin/env groovy
def generateManifest() {
sh "..."
echo "..."
}
In the console log ( stack ):在控制台日志(堆栈)中:
[Pipeline] stage
[Pipeline] { (Publish CF app)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
before loading groovy file
[Pipeline] echo
Loading from deployer.groovy
[Pipeline] load
[Pipeline] // load
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
Update:更新:
It seems the problem was not with loading the file but rather with the contents of the file, where I execute the following which apparently does not play well:似乎问题不在于加载文件,而在于文件的内容,我在其中执行以下显然效果不佳的命令:
sh "node $(pwd)/config/mustacher manifest.template.yml config/environments/common.json config/environments/someFile.json"
echo "..."
When only the echo
is there, this is the stack .当只有
echo
存在时,这就是 stack 。
So not the sh "node ..."
nor the echo
work.所以不是
sh "node ..."
也不是echo
工作。 Even changing it just to sh "pwd"
fails as well.即使将其更改为
sh "pwd"
也会失败。 What could it be?会是什么呢? the syntax in the file?
文件中的语法? the way it is called in the pipeline?
它在管道中的调用方式?
If I will make the same node call in the pipeline (for example in the withCredentials
if
statement, it works.如果我将在管道中进行相同的节点调用(例如在
withCredentials
if
语句中,它会起作用。
Add a return this
to the bottom of the deployer.groovy
file, and then change you load
step to use relative path and extension to groovy file like load('deployer.groovy')
.将
return this
添加到deployer.groovy
文件的底部,然后更改load
步骤以使用相对路径和扩展名到 groovy 文件,如load('deployer.groovy')
。
The return this
is documented on jenkins.io : jenkins.io上记录了此
return this
:
Takes a filename in the workspace and runs it as Groovy source text.
获取工作区中的文件名并将其作为 Groovy 源文本运行。 The loaded file can contain statements at top level or just load and run a closure.
加载的文件可以包含顶层的语句,或者只是加载和运行一个闭包。 For example:
例如:
def pipeline node('slave') { pipeline = load 'pipeline.groovy' pipeline.functionA() } pipeline.functionB()
pipeline.groovy
管道.groovy
def pipelineMethod() { ...code } return this
Where pipeline.groovy
defines functionA and functionB functions (among others) before ending with return this
在以
return this
结尾之前, pipeline.groovy
定义了 functionA 和 functionB 函数(以及其他函数)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.