导入python lib包,根据需求自行删减
import os
import pathlib
import re
import time
from tkinter import *
from kubernetes import client, config
获取k8s master操作yaml文件
1.自建集群可以在master节点获取
# cat $HOME/.kube/config
2.云平台可以在集群信息列表查看获取
3.本文章使用的windowsPath是windows路径
# 全局变量获取用户家目录
home = pathlib.Path.home()
os_path = home / 'cert'
config_file = os_path / 'k8s.yaml'
windowsPathTemp = str(config_file).split('\\')
windowsPathTemp[0] = windowsPathTemp[0]
windowsPath = '/'.join(windowsPathTemp)
本文章是通过yaml文件配置集群操作,也可以通过其他方式配置集群API文件
操作pod更新
#下面四个参数可通过函数或者前端发送接受
name=nginx #pod名称
namespace=default #命名空间
servers_list=nginx #镜像名称
text_output=v1.1.1 #tag版本
config.kube_config.load_kube_config(config_file=windows_path)
_AppsV1Api = client.AppsV1Api()
old_deploy = _AppsV1Api.read_namespaced_deployment(
name=name,
namespace=namespace,
)
img_domain_rule = r"([^?]{1,}\.[^?]{1,}\.com).*\:.*" #获取镜像域名正则表达式
oldImgdoamin = re.findall(img_domain_rule, old_deploy.spec.template.spec.containers[0].image)[0]
images = "{0}/test/{1}:{2}".format(oldImgdoamin, servers_list, text_output) #替换要更新的名字与标签
old_deploy.spec.template.spec.containers[0].image = images
_AppsV1Api.patch_namespaced_deployment(
name=name,
namespace=namespace,
body=old_deploy
)
pod重启
audit_overseas_admin_name=nginx #需要重启的pod名称
audit_domestic=default #命名空间
config.kube_config.load_kube_config(config_file=windowsPath)
_AppsV1Api = client.CoreV1Api()
res = _AppsV1Api.list_pod_for_all_namespaces() #获取所有pod名字
for i in res.items: #遍历所有pod换行去除
if i.metadata.namespace == audit_domestic:
deploy_pod_name += "%s\n" % i.metadata.name
rename = "{0}.*".format(audit_overseas_admin_name)
pod_name = re.findall(rename, deploy_pod_name)
for pod_name_list in pod_name: #遍历删除
client.CoreV1Api().delete_namespaced_pod(namespace=audit_domestic,
name=pod_name_list)
time.sleep(3) #pod依次删除,默认循环是一次性全部重启,需要添加约束