# !/usr/bin/python3
# -*- coding: utf-8 -*-
'''replace_namespace_deployment,快速替换deployment需要升级或回滚的镜像'''
import os
from kubernetes import client, config
from kubernetes.client.rest import ApiException
import requests
import time
print(time.time())
r = requests.get("https://zhangjiakou.aliyuncs.com/common/test/config")
#print(r.text)
def read_deployment(name, namespace, update_image):
body = api_instance.read_namespaced_deployment(name, namespace)
# 修改镜像版本为指定
body.spec.template.spec.containers[0].image = update_image
return body
def replace_deployment(name, namespace, body):
try:
api_response = api_instance.replace_namespaced_deployment(name, namespace, body)
print(" 33[0;32m{} 中deployment : {} {}更新完成 33[0m".format(namespace, name, new_image))
except ApiException as e:
print("Exception when calling AppsV1Api->replace_namespaced_deployment: %sn" % e)
if __name__ == "__main__":
# kubernetes生成时/root目录下.kube目录下的认证配置文件
kube_conf = os.path.join('/Users/hong/.kube/config')
print(kube_conf)
config.load_kube_config(kube_conf)
# config.kube_config.load_kube_config_from_dict(r.text)
api_instance = client.AppsV1Api()
# 传入参数配置
# name = 'bsopconsole-group-1-12'
# namespace = 'serucity-dirac'
#update_image = 'registry-vpc.cn-north-2-gov-1.aliyuncs.com/lippi-base-test/bsopconsole:test.20210514195010'
#body = read_deployment(name, namespace, update_image)
# print(body)
# replace_deployment(name, namespace, body)
# deployments=api_instance.list_namespaced_deployment(namespace='serucity-dirac', watch=False)
v1 = client.CoreV1Api()
app_name = 'security-dirac'
# while 1:
ret = api_instance.list_namespaced_deployment(namespace='serucity-dirac', watch=False)
# ret = v1.list_namespaced_pod(namespace='serucity-dirac', watch=False)
for i in ret.items:
if i.metadata.labels['edas.oam.acname'] == app_name and i.status.replicas:
new_image_id = 20210527100520
deployment_name = i.metadata.name
namespace = i.metadata.namespace
old_image = i.spec.template.spec.containers[0].image
new_image = old_image[:-14] + str(new_image_id)
# print(i.status)
#print("%st%st%st%s" % (deployment_name, namespace, old_image, new_image))
# body = api_instance.read_namespaced_deployment(deployment_name, namespace)
# available_replicas = body.status.replicas
# ready_replicas = body.status.ready_replicas
# replicas = body.status.replicas
# unavailable_replicas = body.status.unavailable_replicas
# if unavailable_replicas is None and available_replicas == replicas and replicas == ready_replicas:
# # print("{},available_replicas:{}, ready_replicas:{}, replicas:{}".format(deployment_name,
# # available_replicas,
# # ready_replicas, replicas))
# #print(body.status)
# pass
# else:
# print("{},available_replicas:{}, ready_replicas:{}, replicas:{}".format(deployment_name,
# available_replicas,
# ready_replicas, replicas))
# #print(body.status)
# pass
body = read_deployment(deployment_name, namespace, new_image)
print(body)
replace_deployment(deployment_name, namespace, body)