1、业务在有些情况下需要选择不同的环境来构建服务,使用同一套代码读取不同的配置
2、jenkins使用如下配置即可实现构建环境的选择
2.1、配置构建选项
2.2、配置构建tag
2.3、选择构建时间参数
3、使用如下pipeline实现jenkins构建环境选择
pipeline {
agent any
environment {
server_name = "phl-clean-service"
image_name = "192.168.122.150/risk-test/phl-clean-service:${date}"
}
parameters {
choice(
choices: ['test', '190'],
description: '选择构建环境',
name: 'ENVIRONMENT'
)
}
stages {
stage('Printenv') {
steps {
script{
sh 'printenv'
}
}
}
stage('pull code') {
steps {
checkout([$class: 'GitSCM',
branches: [[name: "${params.TAG}"]],
extensions: [],
userRemoteConfigs: [[credentialsId: 'xxxxxx',
url: 'https://codeup.aliyun.com/62d8eebfdasf87dgd6/hc-risk/hc-risk-phl.git']]])
updateGitlabCommitStatus(name: env.STAGE_NAME, state: 'success')
script{
env.BUILD_TASKS = env.STAGE_NAME + "√..." + env.TAB_STR
}
}
}
stage('Code Build'){
steps {
retry(2) { sh "/opt/maven/bin/mvn -U -pl risk-clean/clean-service -am -Dmaven.test.skip=true clean package " }
updateGitlabCommitStatus(name: env.STAGE_NAME, state: 'success')
script{
env.BUILD_TASKS += env.STAGE_NAME + "√..." + env.TAB_STR
}
}
}
stage('Docker Build') {
steps {
script {
// 根据选择的环境执行不同的构建操作
if (params.ENVIRONMENT == "test") {
retry(2) {
sh '''
docker build -t "${image_name}" --build-arg projectEnv=${ENVIRONMENT} -f risk-clean/clean-service/Dockerfile .
docker login -urisk-test -pAa123456 192.168.122.150
docker push ${image_name} && docker rmi ${image_name}
'''
}
} else if (params.ENVIRONMENT == "190") {
retry(2) {
sh '''
docker build -t "${image_name}" --build-arg projectEnv=${ENVIRONMENT} -f risk-clean/clean-service/Dockerfile .
docker login -urisk-test -pAa123456 192.168.122.150
docker push ${image_name} && docker rmi ${image_name}
'''
}
} else {
echo '未选择有效的环境,请选择'
}
}
}
}
stage('Application Deploy'){
steps {
retry(2) { sh 'kubectl --kubeconfig /opt/kubernetes/config set image -n risk-phl deploy/"${server_name}" "${server_name}"="${image_name}"' }
//retry(2) { echo 'test' }
updateGitlabCommitStatus(name: env.STAGE_NAME, state: 'success')
script{
env.BUILD_TASKS += env.STAGE_NAME + "√..." + env.TAB_STR
}
}
}
}
}
4、执行完成后的Pipeline如下