您可以像这里一样使用和配置shared library(一个git repo):https://github.com/lvthillo/shared-library。您需要在 Jenkins 全局配置中进行配置。
它包含一个文件夹vars/。在这里,您可以管理管道和 groovy 脚本,例如我的 slackNotifier.groovy。该脚本只是一个用于在 Slack 中打印构建结果的 groovy 脚本。
在 jenkins 管道作业中,我们将导入我们的共享库:
@Library('name-of-shared-pipeline-library')_
mavenPipeline {
//define parameters
}
在上述情况下,管道也在共享库中,但这不是必需的。
您可以在作业本身中编写您的管道,然后只从管道中调用函数,如下所示:
这是共享库中的脚本:
// vars/sayHello.groovy
def call(String name = 'human') {
echo "Hello, ${name}."
}
在您的管道中:
final Lib= library('my-shared-library')
...
stage('stage name'){
echo "output"
Lib.sayHello.groovy('Peter')
}
...
编辑:
在新的声明式管道中,您可以使用:
pipeline {
agent { node { label 'xxx' } }
options {
buildDiscarder(logRotator(numToKeepStr: '3', artifactNumToKeepStr: '1'))
}
stages {
stage('test') {
steps {
sh 'echo "execute say hello script:"'
sayHello("Peter")
}
}
}
post {
always {
cleanWs()
}
}
}
def sayHello(String name = 'human') {
echo "Hello, ${name}."
}
输出:
[test] Running shell script
+ echo 'execute say hello script:'
execute say hello script:
[Pipeline] echo
Hello, Peter.
[Pipeline] }
[Pipeline] // stage