既然生产环境与测试环境要分离,就需要各自维护自己的一套环境
通过jenkins里的项目参数可以选择构建在那个环境
生产环境与测试环境
- 使用不同的数据库配置文件
- docker实例端口也要配置不相同的端口
- docker 启动不同的镜像,使用不同的容器的名字
所以需要通过变量来区分生产环境与测试环境,jenkinsfile如下
1 pipeline { 2 agent { 3 label 'master' 4 } 5 6 environment { 7 docker_image = 'jeesite4' 8 docker_container = 'iJeesite4' 9 } 10 11 parameters { 12 string(name: 'branch', defaultValue: 'master', description: 'Git branch') 13 choice(name: 'env', choices: ['prod', 'qa'], description: 'Environment Type') 14 } 15 16 stages{ 17 stage('同步源码') { 18 steps { 19 git url:'https://gitee.com/testingl/JeeSite4.git', branch:'${branch}' 20 } 21 } 22 23 stage('设定配置文件'){ 24 steps{ 25 sh ''' 26 . ~/.bash_profile 27 28 if [[ "${env}" == "prod" ]]; then 29 export mysql_ip=${mysql_prod_ip} 30 export mysql_port=${mysql_prod_port} 31 else 32 export mysql_ip=${mysql_qa_ip} 33 export mysql_port=${mysql_qa_port} 34 fi 35 36 export os_type=`uname` 37 cd ${WORKSPACE}/web/bin/docker 38 if [[ "${os_type}" == "Darwin" ]]; then 39 sed -i "" "s/mysql_ip/${mysql_ip}/g" application-${env}.yml 40 sed -i "" "s/mysql_port/${mysql_port}/g" application-${env}.yml 41 sed -i "" "s/mysql_user/${mysql_user}/g" application-${env}.yml 42 sed -i "" "s/mysql_pwd/${mysql_pwd}/g" application-${env}.yml 43 sed -i "" "s/<env>/${env}/g" Dockerfile-param 44 else 45 sed -i "s/mysql_ip/${mysql_ip}/g" application-${env}.yml 46 sed -i "s/mysql_port/${mysql_port}/g" application-${env}.yml 47 sed -i "s/mysql_user/${mysql_user}/g" application-${env}.yml 48 sed -i "s/mysql_pwd/${mysql_pwd}/g" application-${env}.yml 49 sed -i "s/<env>/${env}/g" Dockerfile-param 50 fi 51 ''' 52 } 53 } 54 55 stage('Maven 编译'){ 56 steps { 57 sh ''' 58 cd ${WORKSPACE}/root 59 mvn clean install -Dmaven.test.skip=true 60 61 cd ${WORKSPACE}/web 62 mvn clean package spring-boot:repackage -Dmaven.test.skip=true -U 63 ''' 64 } 65 } 66 67 stage('停止 / 删除 现有Docker Container/Image '){ 68 steps { 69 script{ 70 try{ 71 sh 'docker stop $docker_container-$env' 72 }catch(exc){ 73 echo "The container $docker_container-${params.env} does not exist" 74 } 75 76 try{ 77 sh 'docker rm $docker_container-$env' 78 }catch(exc){ 79 echo "The container $docker_container-${params.env} does not exist" 80 } 81 82 try{ 83 sh 'docker rmi $docker_image-$env' 84 }catch(exc){ 85 echo "The docker image $docker_image-${params.env} does not exist" 86 } 87 } 88 } 89 } 90 91 stage('生成新的Docker Image'){ 92 steps { 93 sh ''' 94 cd ${WORKSPACE}/web/bin/docker 95 rm -f web.war 96 cp ${WORKSPACE}/web/target/web.war . 97 docker build -t $docker_image-$env -f Dockerfile-param . 98 ''' 99 } 100 } 101 102 stage('启动新Docker实例'){ 103 steps { 104 sh ''' 105 if [[ "$env" == "prod" ]]; then 106 export port="8888" 107 else 108 export port="8811" 109 fi 110 111 docker run -d --name $docker_container-$env -p $port:8980 $docker_image-$env 112 ''' 113 } 114 } 115 } 116 }
注意:这里我们需要启动连个不同名字的mysql容器,名字和application-${env}.yml一致
jenkins构建流水线任务,配置pipeline SCM拉取代码,指定流水线执行脚本
构建一次之后,jenkins界面中会自动生成参数配置
构建结果