GitOps实战
什么是GitOPs
GitOps是以开发人员(developer)为中心的,针对云原生应用的持续部署流程。简单来说developer以管理代码的方式来管理kubernetes的yaml文件,kubernetes的operator负责把git仓库中的yaml文件应用到kubernetes集群中,从而实现应用的部署。
GitOps的适用场景
git有完整的文件修改记录,这比较适合对合规性要求比较高的公司。
实施GitOps的注意事项
敏感信息比如密码不应该保存在git上。
实例演示
开发和部署流程的设计
采用”主干开发模式“,提交到master分支的代码就通过CI、CD流水线部署到test环境。通过在master分支上打tag的方式进行正式的版本分布,tag的名称就是软件的版本号,正式发布的版本会被部署到stage环境中。
CI流水线再推送完docker镜像后更新对应的部署文件并推送至git仓库。
测试需要的资源
- Gitlab
- kubesphere
- argocd
- Nexus
测试代码
测试程序是在nginx上部署一个静态的html页面。整个项目包含一个html页面,一个Dockerfile,还有gitlab-ci.yml
index.html
Version 1.0.0
Dockerfile
FROM nginx:1.20.2
COPY index.html /usr/share/nginx/html
EXPOSE 80
.gitlab-ci.yml
# 在CICD环境变量中定义下面的变量
# DOCKER_REPO
# 可以用做docker image版本的变量,CI_COMMIT_TAG,CI_COMMIT_SHA,CI_COMMIT_REF_NAME
stages:
- build
- dockerImage
- deploy
build_product:
stage: build
only:
- master
- tags
script:
- echo "start building"
#- npm install
#- npm run build
artifacts:
name: "$CI_PROJECT_NAME$CI_COMMIT_REF_NAME"
paths:
- dist/
expire_in: 1 day
build_latest_docker_image:
stage: dockerImage
only:
- master
script:
- echo "building image"
- echo $DOCKER_PWD | docker login -u $DOCKER_USER --password-stdin $DOCKER_REPO
- docker rmi $(docker images -qa) || echo "not find the image"
- docker build -t $DOCKER_REPO/$CI_PROJECT_NAME:$CI_COMMIT_SHORT_SHA .
- docker push $DOCKER_REPO/$CI_PROJECT_NAME:$CI_COMMIT_SHORT_SHA
build_production_docker_image:
stage: dockerImage
only:
- tags
script:
- ls || echo "did not find dist"
- docker rmi $(docker images -qa) || echo "not find the image"
- echo $CI_COMMIT_REF_NAME
- docker build -t $DOCKER_REPO/$CI_PROJECT_NAME:$CI_COMMIT_TAG .
- docker login -u $DOCKER_USER -p $DOCKER_PWD $DOCKER_REPO
- docker push $DOCKER_REPO/$CI_PROJECT_NAME:$CI_COMMIT_TAG
deploy_to_test:
stage: deploy
only:
- master
script:
- echo "deploying to test $CI_COMMIT_SHORT_SHA"
- cd ~/gitops
- ls
- git pull || echo "pull failed, try again"
- sed -i "s/mywebdemo:\(.*\)/mywebdemo:$CI_COMMIT_SHORT_SHA'/g" mywebdemo/test/deployment.yaml
- git add .
- git commit -m "update from gitlab ci"
- echo "start pushing"
- git push
deploy_to_stage:
stage: deploy
script:
- echo "start deploying to production "
- echo "deploying to test"
- cd ~/gitops
- ls
- git pull || echo "pull failed, try again"
- sed -i "s/mywebdemo:\(.*\)/mywebdemo:$CI_COMMIT_TAG'/g" mywebdemo/stage/deployment.yaml
- git add .
- git commit -m "update from gitlab ci"
- pwd
- git push
#- git push || echo "try again"
#- git push
- ls
only:
- tags
Gitlab-runner免密更新gitops仓库
gitlab-runner需要向git仓库推送配置信息,所以它需要有git的权限。
把公钥添加到gitlab server上,在gitlab-runner所在的机器上的gitlab-runner这个用户下做如下配置:
vim ~/.ssh/config
Host gitlab
HostName gitlab.tech.vnet.tv
User git
Port 8022 #gitlab server是用docker安装的,8022是影射端口
#IdentityFile ~/.ssh/id_rsa
ssh -T gitlab
cd gitops #配置文件的git仓库
git remote set-url origin git@gitlab:yourname/gitops.git