springcloud项目架构复杂,不同于springboot架构,使用单一内容的.gitlab-ci.yml文件无法达到想要的效果,这里说一个小诀窍
简单来说,就是在使用.gitlab-ci.yml文件时,不直接进入具体的子项目模块中找到jar包和Dockerfile进行构建镜像,而是先设置一个变量为当前要更新的子模块,然后使用多个if条件语句在项目跟目录下创建新目录,把要更新的子模块jar包和Dockerfile复制过来,然后使用artifacts传递这俩文件到下一job阶段,从而实现构建docker镜像的目的
项目架构如下:
.gitlab-ci.yml文件内容如下:
# SpingCloud项目,每次更新提交时需要修改变量CURRENT_PROJECT的值
variables:
DOCKER_DRIVER: overlay2
MAVEN_CLI_OPTS: "-s .m2/settings.xml --batch-mode"
MAVEN_OPTS: "-Dmaven.repo.local=.m2/repository"
# CI_PROJECT_DIR 项目根目录的预定义全局变量
CURRENT_PROJECT: jdd-boot-module-thirdparty
# 每次需要修改这个 jdd-cloud-gateway,jdd-cloud-system-start, jdd-boot-module-cobrandedcard,jdd-boot-module-thirdparty
cache:
paths:
- .m2/repository/
stages:
- package
- build
maven_step:
tags:
- maven
stage: package
script:
- mvn clean package -Dmaven.test.skip=true
- if [ $CURRENT_PROJECT == "jdd-cloud-gateway" ] || [ $CURRENT_PROJECT == "jdd-cloud-system-start" ]; then mkdir -p $CI_PROJECT_DIR/target && cd jdd-cloud-module && cp $CURRENT_PROJECT/target/*.jar $CI_PROJECT_DIR/target/ && cp $CURRENT_PROJECT/Dockerfile $CI_PROJECT_DIR/target/; fi
- if [ $CURRENT_PROJECT == "jdd-boot-module-cobrandedcard" ] || [ $CURRENT_PROJECT == "jdd-boot-module-thirdparty" ]; then mkdir -p $CI_PROJECT_DIR/target && cp $CURRENT_PROJECT/target/*.jar $CI_PROJECT_DIR/target/ && cp $CURRENT_PROJECT/Dockerfile $CI_PROJECT_DIR/target/; fi
artifacts:
paths:
- $CI_PROJECT_DIR/target/*
only:
- test
develop_docker_step:
tags:
- docker
stage: build
script:
- export TAG=`date "+%Y%m%d%H%M%S"`
- cd $CI_PROJECT_DIR/target && ls -al
- docker build -t $DOCKER_HTTP/jdd-k8s/$CURRENT_PROJECT:$TAG .
- docker login -u $DOCKER_USER -p $DOCKER_PASSWORD $DOCKER_HTTP
- docker push $DOCKER_HTTP/jdd-k8s/$CURRENT_PROJECT:$TAG
- docker rmi $DOCKER_HTTP/jdd-k8s/$CURRENT_PROJECT:$TAG
# 提交后需要手动更新k8s中使用的docker镜像版本
only:
- test