在外部文件上定义Jenkins管道 [英] Define Jenkins pipeline on an external file

查看:111
本文介绍了在外部文件上定义Jenkins管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有几个具有相同结构和行为的管道作业:更新ansible存储库,使用一些值取决于环境的参数执行剧本,并通过inspec进行测试.我们已经尝试将外部文件中的一般行为抽象出来.

We have several pipeline jobs with the same structure and behavior: update an ansible repository, execute a playbook with some parameters whose value depends on the environment and test with inspec the execution. We've tried to abstract the general behavior in an external file.

JenkinsfileAnsible:

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,以执行管道.

Each environment will have a specific Jenkinsfile that sets the parameters and load the general Jenkinsfile in order to execute the pipeline.

JenkinsfileDev:

JenkinsfileDev:

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

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

代码已经简化,我们可以轻松加载外部文件或执行定义的函数.问题在于,我们想在通用文件中定义管道,就像在每个环境中一样,仅调用它即可,但是我们无法使其正常工作.

The code has been simplified, and we do not have trouble loading the external file or executing defined functions. The problem is that we wanted to define the pipeline inside the general file, as is the same for every environment, and just invoke it, but we can't make it work.

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

We've faced errors as Jenkins can't recognize the pipeline definition in the external file.

有什么建议吗?是不可能的吗?我们缺少什么吗?

Any advice? Is not possible to do? Is there something we are missing?

推荐答案

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

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

The approach would be to have a Jenkinsfile like this:

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

在管道库代码中,类似:

And in the Pipeline Library code, something like:

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'){
           ...
        }
    }
}

您可以将config参数用于不同的环境,甚至可以为不同的环境创建不同的管道.

You can use the config params for different environments or even create different pipelines for the different environments.

希望有帮助.

这篇关于在外部文件上定义Jenkins管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆