期望效果
当修改当前分支代码时,会自动触发gitlabci.yml脚本,进行构建、部署到k8s集群中。
创建gitlab项目
cat .gitlab-ci.yml
stages:
- build
- deploy
build-image:
stage: build
tags:
- test
only:
- master
script:
- cd $BUILD_DIR
- docker build -t registry.cn-zhangjiakou.aliyuncs.com/moran/hello-world:v1 ./
- docker push registry.cn-zhangjiakou.aliyuncs.com/moran/hello-world:v1
deploy-service:
stage: deploy
tags:
- test
only:
- master
script:
- cd $WORK_DIR
- if [ ! -d "deploy-files-k8s" ]; then git clone https://gitlab.xiaomor.com:9443/test-k8s/deploy-files-k8s.git; else rm -rf deploy-files-k8s; git clone https://gitlab.xiaomor.com:9443/test-k8s/deploy-files-k8s.git; fi
- cd deploy-files-k8s
- pod_list=$(kubectl get pods|grep hello|awk '{print $1}')
- kubectl delete pod $pod_list
cat Dockerfile
FROM docker.io/library/python
RUN mkdir -p /home/work
COPY ./hello.py /home/work/
RUN chmod +x /home/work/*
RUN pip install flask
WORKDIR /home/work
USER root
CMD ["python","hello.py"]
cat hello.py
from flask import Flask
app = Flask(__name__)
# hhhhh
@app.route("/hello", methods=["get"])
def hello():
return "hello world"
if __name__ == '__main__':
app.run(host='0.0.0.0')
找到项目中的api-url及token,需要在后面注册gitlab-runner中用到。
docker创建gitlab-runner
搜索gitlab-runner镜像
启动gitlab-runner容器
docker run -d --privileged=true --name gitlab-runner --restart always -v /srv/gitlab-runner/config:/etc/gitlab-runner -v /var/run/docker.sock:/var/run/docker.sock -v /usr/bin/docker:/usr/bin/docker gitlab/gitlab-runner:latest
注册gitlab项目
docker exec -it gitlab-runner bash
gitlab-runner register
按照要求依次输入信息:
上图中的url、token、名字test、tag为test、shell
注册成功后,可以在gitlab的CICD界面看到runner状态。
定义gitlabci.yml中的相关参数
由于我们更新的是k8s服务,所以需要在runner中配置好k8s环境,所以需要安装相关包:
apt update
apt install kubectl kubelet kubeadm -y
systemctl enable kubelet
把k8s的配置文件拷贝到gitlab-runner里:
放在/home/gitlab-runner/.kube/config
导入环境变量,添加到/etc/profile中
export KUBECONFIG=/home/gitlab-runner/.kube/config
source /etc/profile
将k8s节点信息写入/etc/hosts
执行kubectl命令查看是否成功
kubectl get nodes
此时,已完成全部步骤,修改gitlab下代码查看pipline:
没有异常后查看集群中pod状态即可。