您必须创建一个共享库来实现我将要提出的建议。对于共享库的实现,您可以查看以下帖子:
Using Building Blocks in Jenkins Declarative Pipeline
Upload file in Jenkins input step to workspace(主要是图片,方便看东西)
现在,如果您想使用可以跨多个项目(作业)重用的 Jenkinsfile(一种 模板),那么这确实是可能的。
一旦您创建了一个包含vars 目录的共享库存储库,那么您只需在vars 目录中创建一个Groovy 文件(比如说commonPipeline.groovy)。
这是一个有效的示例,因为我之前在多个作业中使用过它。
$ cat shared-lib/vars/commonPipeline.groovy
// You can create function(s) as shown below, if required
def someFunctionA() {
// Your code
}
// This is where you will define all the stages that you want
// to run as a whole in multiple projects (jobs)
def call(Map config) {
pipeline {
agent {
node { label 'slaveA || slaveB' }
}
environment {
myvar_Y = 'apple'
myvar_Z = 'orange'
}
stages {
stage('Checkout') {
steps {
deleteDir()
checkout scm
}
}
stage ('Build') {
steps {
script {
check_something = someFunctionA()
if (check_something) {
echo "Build!"
# your_build_code
} else {
error "Something bad happened! Exiting..."
}
}
}
}
stage ('Test') {
steps {
echo "Running tests..."
// your_test_code
}
}
stage ('Deploy') {
steps {
script {
sh '''
# your_deploy_code
'''
}
}
}
}
post {
failure {
sh '''
# anything_you_need_to_perform_in_failure_step
'''
}
success {
sh '''
# anything_you_need_to_perform_in_success_step
'''
}
}
}
}
有了上面的 Groovy 文件,您现在要做的就是在您的各种 Jenkins 项目中调用它。由于您的 Jenkins 项目中可能已经有一个现有的 Jenkinsfile(如果没有,请创建它),您只需将该文件的现有内容替换为以下内容:
$ cat Jenkinsfile
// Assuming you have named your shared-library as `my-shared-lib` & `Default version` to `master` branch in
// `Manage Jenkins` » `Configure System` » `Global Pipeline Libraries` section
@Library('my-shared-lib@master')_
def params = [:]
params=[
jenkins_var: "${env.JOB_BASE_NAME}",
]
commonPipeline params
注意:正如您在上面看到的,我正在调用commonPipeline.groovy 文件。因此,您所有庞大的 Jenkinsfile 将减少到只有五六行代码,而这几行代码也将在所有这些项目中通用。另请注意,我在上面使用了jenkins_var。它可以是任何名称。它实际上并未使用,但 是运行管道所必需的。一些 Groovy 专家可以澄清这部分。
参考:https://www.jenkins.io/blog/2017/10/02/pipeline-templates-with-shared-libraries/