gitlabCI自动化更新k8s服务

期望效果

当修改当前分支代码时,会自动触发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状态即可。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值