Created
April 6, 2018 22:27
-
-
Save bernardoVale/cf4fc663b11ee7425524e3ca51aa6cda to your computer and use it in GitHub Desktop.
K8s client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from kubernetes import client, config | |
from datetime import datetime | |
def extract_days(pod_timestamp): | |
delta = datetime.now().replace(tzinfo=None) - pod_timestamp.replace(tzinfo=None) | |
return delta.days | |
config.load_kube_config() | |
v1_apps = client.AppsV1beta1Api() | |
deployment = v1_apps.read_namespaced_deployment(name='acdclegacy-production', namespace='acdc-legacy') | |
print(deployment) | |
# print("Listing pods with their IPs:") | |
v1 = client.CoreV1Api() | |
ret = v1.list_namespaced_pod(namespace='acdc-legacy', label_selector="acdclegacy-production=true") | |
pods_need_replacement = 0 | |
replace_list = [] | |
for pod in ret.items: | |
created = pod.metadata.creation_timestamp.replace(tzinfo=None) | |
name = pod.metadata.name | |
id = pod.metadata.uid | |
days_old = extract_days(created) | |
print("Pod {} is {} days old".format(name, days_old)) | |
if days_old > 0: | |
pods_need_replacement += 1 | |
replace_list.append(pod) | |
# Scale first | |
if pods_need_replacement > 0: | |
deployment.spec.replicas = deployment.spec.replicas + pods_need_replacement | |
deployment = v1_apps.patch_namespaced_deployment_scale(name='acdclegacy-production', namespace='acdc-legacy', body=deployment) | |
# Wait for running | |
print(deployment) | |
deployment.spec.replicas = deployment.spec.replicas - pods_need_replacement | |
deployment = v1_apps.patch_namespaced_deployment_scale(name='acdclegacy-production', namespace='acdc-legacy', body=deployment) | |
# Delete old pods | |
for pod in replace_list: | |
v1.delete_namespaced_pod(name=pod.metadata.name, namespace='acdc-legacy', body=pod) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment