不会飞的渡渡鸟原创,转载请说明出处
当jenkins部署的项目有很多相同的步骤的时候,就可以使用jenkins公共库引入的方式构建项目。
官方文档示例: https://jenkins.io/doc/book/pipeline/shared-libraries/
开启pipeline公共库
系统管理 — Global Pipeline Libraries
在这里面选择使用Git管理你的公共库资源
Name 是名称,这里写: pipeline-library
Default version 就是Git分支
这里我使用了git进行代码仓库管理,目录结构如下
src groovy源文件
在pipeline中使用公共库,首先需要在第一行定义
@Library('pipeline-library')_
示例 – 引用公共变量
src/com/ddn/ddn.groovy
#!/usr/bin/env groovy package com.GlobalVars class GlobalVars { static String git_repo = "*/test" //分支 static String maven_args = "-DskipTests clean package -U -P test" }
这里我写了两个变量
- git_repo git分支
- maven_args maven打包命令
Jenkins Pipeline示例
@Library('pipeline-library')_ import com.ddn.GlobalVars node("master") { stage('Git Clone') { checkout([$class: 'GitSCM', branches: [[name: GlobalVars.git_repo]], doGenerateSubmoduleConfigurations: false,userRemoteConfigs: [[credentialsId: 'git拉取代码id', url: 'gitxxxxxxx']]]) } stage('Maven build'){ sh "mvn ${GlobalVars.maven_args} -f pom.xml" } }
- git分支使用 GlobalVars.git_repo 变量
- maven打包使用: GlobalVars.maven_args 变量
项目较多需要统一更改一些公共变量时可以采取这种方法。
如果你多个项目构建步骤相同,可以用DSL把相同的构建步骤写入公共变量vars里面
示例如下:
这是一个k8s项目部署的示例
vars/ddn_deploy.groovy
def call(Map config) { node ('jnlp-slave'){ //阿里云私服配置 def registry_url = "registry-vpc.cn-beijing.aliyuncs.com" def registry_auth = "docker-registry-aliyun" def image_name = "${registry_url}/project/:${config.app_name}_${env.BUILD_ID}" // stage('Git Clone') { checkout([$class: 'GitSCM', branches: [[name: '*/test']], doGenerateSubmoduleConfigurations: false,userRemoteConfigs: [[credentialsId: 'git账号ID', url: config.git_url]]]) } stage('Maven build'){ sh "mvn -DskipTests clean package -U -P test -f ${config.pom_path}" } stage("Docker build"){ sh """ /bin/cp /data/k8s-file/Dockerfile_template Dockerfile sed -i s#JAR_FILE=.*#JAR_FILE=${config.jar_file}# Dockerfile """ docker.withRegistry("https://" + registry_url,registry_auth) { def customImage = docker.build(image_name) customImage.push() } } stage("k8s deploy") { kubernetesDeploy configs: 'Deployment.yml', kubeconfigId: "K8s凭据id",textCredentials: [serverUrl: 'https://'] } } }
jenkins pipeline示例
这是一个通过jenkins部署java项目的示例,定义app_name,git地址,pom地址,打包好的jar文件地址,
@Library('pipeline-library')_ def map = [ app_name: "ddn-test", git_url : "https://git.ddn.com/xxxxx.git", pom_path: "ddn/pom.xml", jar_file: "ddn/target/ddn.jar" ] podTemplate(label: 'jnlp-slave', cloud: 'kubernetes'){ ddn_deply map }
每一个项目只需要定义四个变量即可,构建步骤都通过vars/ddn_deploy.groovy文件控制,这种做法的好处在于便于维护,如果想要更改构建步骤只需更改ddn_deploy.groovy文件,而无需对每一个项目都进行更改。