是否可以创建管道模板,以便Jenkins自动构建管道?

时间:2017-06-12 11:43:35

标签: jenkins groovy jenkins-pipeline

我写了以下管道:

import groovy.transform.Field

channel = '#jenkins-dev-alerts'
@Field def stage_name, emailadd
def docker_creds = 'XXXXXXXXX'
def git_creds = 'XXXXXXXXX'

fileLoader.withGit('git@bitbucket.org:company/pipeline_utils.git', 'master', git_creds, ''){
    utils = fileLoader.load('functions.groovy');
}

def run_in_stage(String stage_name, Closure command){
    utils.run_in_stage(stage_name, command, emailadd)
}

node('docker') {
    timestamps {
    run_in_stage('Checkout', {
        checkout([$class: 'GitSCM',
            userRemoteConfigs: [[credentialsId: git_creds,
            extensions: [[$class: 'LocalBranch', localBranch: "**"]],
            url: 'git@bitbucket.org:fdnainc/research.git']]])
        currentBuild.displayName = "#${BUILD_NUMBER} | ${env.BRANCH}"
        })

    run_in_stage('Build', {
        withCredentials([
            [$class: 'UsernamePasswordMultiBinding', credentialsId: docker_creds, usernameVariable: 'D_USER', passwordVariable: 'D_PASS'],
        ]){
          sh """
            docker login company-docker.jfrog.io -u \${D_USER} -p \${D_PASS}
            export GIT_COMMIT=\$(git rev-parse --short HEAD)
            export GIT_BRANCH=\$(git rev-parse --abbrev-ref HEAD)
            docker-compose build
            """
          }
      })

    run_in_stage('Test', {
        sh """
          docker-compose down
          docker-compose up --abort-on-container-exit || true
          """
          junit 'reports/**/*.xml'
          sh 'docker volume prune -f'
    })

    if (currentBuild.result == 'UNSTABLE') {
        currentBuild.result = 'FAILURE'
    }
    if (currentBuild.result == null) {
      currentBuild.result = "SUCCESS"
    }
  }
}
if (currentBuild.result == "FAILURE") {
    utils.notifyOnFail(stage_name)

} else if (currentBuild.result == "SUCCESS") {
  node ('docker') {
    run_in_stage('Deploy', {
      sh 'docker-compose push'
      utils.notifyOnSuccess(stage_name)
    })
  }
}

此管道构建一个项目。

我有大约10个项目需要使用与此管道中相同的阶段构建。

我可以复制&将此管道的骨架粘贴到其他项目中,但我知道必须有更好的方法来做到这一点,因此管理起来会更容易。

任何人都知道如何做到这一点?

1 个答案:

答案 0 :(得分:1)

几周前,我问自己一个类似的问题。我在这里发布了我的解决方案:Jenkins pipeline template

我们的想法是使用提供管道模板的全局变量创建Shared Library。这不是文档中广泛描述的内容,但最近我发现以下部分提示了类似的解决方案:https://jenkins.io/doc/book/pipeline/shared-libraries/#defining-a-more-structured-dsl

相关问题