一.介绍
前一篇,介绍了ASP.NET Core部署到K8S上,下面介绍我们在发布新一版本中怎么通过Gitlab CI自动给镜像打版本并部署到K8S上.
二.我们通过GitLab CI/CD 变量
不废话,先上代码:
stages:
- build
- test
- package
- deploy
- release
build:
stage: build
script:
- cd Deploy.API
- dotnet build
test:
stage: test
script:
- dotnet restore
- dotnet build
- cd minicover
- dotnet restore
- dotnet minicover instrument --workdir ../ --assemblies Deploy.API.UnitTests/bin/**/*.dll --sources Deploy.API/**/*.cs
- dotnet minicover reset
- cd ..
- dotnet test --no-build Deploy.API.UnitTests/Deploy.API.UnitTests.csproj
- cd minicover
- dotnet minicover report --workdir ../ --threshold 10
- dotnet minicover uninstrument --workdir ../
package:
stage: package
script:
- cd Deploy.API
- docker build -t deploy:test .
#- docker login --username $ALIYUN_NAME --password $ALIYUN_TOKEN registry.cn-hangzhou.aliyuncs.com #阿里云仓库
#- docker tag deploy:test registry.cn-hangzhou.aliyuncs.com/windows_evan/deploy:test
#- docker push registry.cn-hangzhou.aliyuncs.com/windows_evan/deploy:test
- docker login --username=evan --password Pwd123456 192.168.0.203 #私有仓库Harbor
- docker tag deploy:test 192.168.0.203/myproject/deploy:test
- docker push 192.168.0.203/myproject/deploy:test
deploy:
stage: deploy
script:
- if [ $(docker ps -aq --filter name=userapi) ]; then docker rm -f userapi;fi
#- docker run -d -p 8003:80 --link db-mysql --network net_db --name userapi registry.cn-hangzhou.aliyuncs.com/windows_evan/deploy:test
- docker run -d -p 8003:80 --link db-mysql --network net_db --name userapi 192.168.0.203/myproject/deploy:test
release:
stage: release
script:
- cd Deploy.API
- sed -i 's/deploy:test/deploy:'$CI_COMMIT_TAG'/g' deploy.yaml
- cat deploy.yaml
- kubectl apply -f deploy.yaml
only:
- tags
package-release:
stage: package
script:
- cd Deploy.API
- docker build -t deploy:$CI_COMMIT_TAG .
- docker login --username=evan --password Pwd123456 192.168.0.203
- docker tag deploy:$CI_COMMIT_TAG 192.168.0.203/myproject/deploy:$CI_COMMIT_TAG
- docker push 192.168.0.203/myproject/deploy:$CI_COMMIT_TAG
only:
- tags
上面的.gitlab-ci.yml 可以看到平常开发人员提交代码先 build , test , package (tag:test) , deploy (docker) ,只有给项目创建tags才会执行package-release , release , 我们通过 sed 命令修改deploy.yaml文件里的test镜像版本.