在外部文件上定义 Jenkins 管道

Define Jenkins pipeline on an external file

我们有几个具有相同结构和行为的流水线作业:更新 ansible 存储库,使用一些值取决于环境的参数执行剧本,并使用检查执行进行测试。我们试图在外部文件中抽象出一般行为。

JenkinsfileAnsible:

#!/usr/bin/env groovy
import groovy.json.JsonOutput

node {
}

def executePlaybook(environment){
  pipeline{

    agent any

    stages{
      stage('Update repository'){
        ...
      }
      stage('Esecute playbook'){
        ...
      }
      stage('Execute tests'){
        ...
      }
    }
  }
}
return this

每个环境都有一个特定的 Jenkinsfile,用于设置参数并加载通用 Jenkinsfile 以执行管道。

JenkinsfileDev:

#!/usr/bin/env groovy
import groovy.json.JsonOutput

node{
    checkout scm
    def ansible = load "../JenkinsfileAnsible"
    ansible.execute_playbook("development")
}

代码已经简化,我们加载外部文件或执行定义的函数时没有问题。问题是我们想在通用文件中定义pipeline,每个环境都一样,然后调用它,但我们不能让它工作。

我们遇到了错误,因为 Jenkins 无法识别外部文件中的管道定义。

有什么建议吗?有没有可能呢?有什么我们遗漏的吗?

您可以使用 https://jenkins.io/doc/book/pipeline/shared-libraries/

中的 Jenkins 管道共享库

方法是拥有一个像这样的 Jenkinsfile:

@Library('your-pipeline') _
thePipeline([param1: val1])

在流水线库代码中,类似于:

def call(Map<String, String> pipelineConfig) {

    pipeline{

        agent any

        stages{
           stage('Update repository'){
           //You can use your pipelineConfig param1 etc.
        }
        stage('Esecute playbook'){
           ...
        }
        stage('Execute tests'){
           ...
        }
    }
}

您可以为不同的环境使用配置参数,甚至可以为不同的环境创建不同的管道。

希望对您有所帮助。