我可以将groovy脚本从相对目录导入到Jenkins文件中吗?
我有一个项目的结构如下:我可以将groovy脚本从相对目录导入到Jenkins文件中吗?,jenkins,groovy,jenkins-pipeline,Jenkins,Groovy,Jenkins Pipeline,我有一个项目的结构如下: / / Jenkinsfile / build_tools / / pipeline.groovy # Functions which define the pipeline / reporting.groovy # Other misc build reporting stuff / dostuff.sh # A shell script used by the pipeline
/
/ Jenkinsfile
/ build_tools /
/ pipeline.groovy # Functions which define the pipeline
/ reporting.groovy # Other misc build reporting stuff
/ dostuff.sh # A shell script used by the pipeline
/ domorestuff.sh # Another pipeline supporting shell-script
simplest-jenkins-shared-library master % cat src/org/foo/Bar.groovy
package org.foo;
def awesomePrintingFunction() {
println "hello world"
}
pipeline {
agent { label 'docker' }
stages {
stage('build') {
steps {
script {
@Library('simplest-jenkins-shared-library')
def bar = new org.foo.Bar()
bar.awesomePrintingFunction()
}
}
}
}
}
是否可以在/build_tools中导入groovy文件,以便在Jenkins文件中使用这两个文件中的函数
理想情况下,我希望有一个类似以下内容的Jenkins文件(伪代码):
我一直关注的是如何在伪代码的第1行编写一个与假装导入语句等效的工作语句
我这么做的原因:build_tools文件夹实际上是许多项目共享的git子模块。我试图为每个项目提供一套通用的构建工具,以阻止每个项目维护人员重新发明这个轮子 加载共享groovy代码的最佳支持方式是通过 如果您有这样的共享库:
/
/ Jenkinsfile
/ build_tools /
/ pipeline.groovy # Functions which define the pipeline
/ reporting.groovy # Other misc build reporting stuff
/ dostuff.sh # A shell script used by the pipeline
/ domorestuff.sh # Another pipeline supporting shell-script
simplest-jenkins-shared-library master % cat src/org/foo/Bar.groovy
package org.foo;
def awesomePrintingFunction() {
println "hello world"
}
pipeline {
agent { label 'docker' }
stages {
stage('build') {
steps {
script {
@Library('simplest-jenkins-shared-library')
def bar = new org.foo.Bar()
bar.awesomePrintingFunction()
}
}
}
}
}
将其推入源代码管理,在jenkins作业中甚至全局配置(这是使用管道时通过jenkins UI执行的唯一操作之一),如以下屏幕截图所示:
然后使用它,例如,如下所示:
/
/ Jenkinsfile
/ build_tools /
/ pipeline.groovy # Functions which define the pipeline
/ reporting.groovy # Other misc build reporting stuff
/ dostuff.sh # A shell script used by the pipeline
/ domorestuff.sh # Another pipeline supporting shell-script
simplest-jenkins-shared-library master % cat src/org/foo/Bar.groovy
package org.foo;
def awesomePrintingFunction() {
println "hello world"
}
pipeline {
agent { label 'docker' }
stages {
stage('build') {
steps {
script {
@Library('simplest-jenkins-shared-library')
def bar = new org.foo.Bar()
bar.awesomePrintingFunction()
}
}
}
}
}
此构建的控制台日志的输出当然包括:
hello world
还有很多其他方法可以编写共享库(比如使用类)和使用它们(比如定义变量,这样您就可以在Jenkins文件中以超级灵活的方式使用它们)。您甚至可以将非groovy文件作为资源加载。查看这些扩展用例。我遵循了这个示例,将pipeline()脚本部分放在Jenkins的pipeline脚本窗口中,在“def bar”行上得到一个红色的“x”,表示“无法解析类org.foo.bar”。我安装了共享库插件,并在Jenkins配置中定义了共享库。我有正确的库dir结构,即src/foo/Bar.groovy。我错过了什么?我知道了。在Bar.groovy中,我将行改为“packegeorg.foo.Bar”,它成功了。