按年龄过滤列出kubernetes使用python API的持久卷声明

2024-09-24 00:28:18 发布

您现在位置:Python中文网/ 问答频道 /正文

正在寻找超过一定时间限制的kubernetes pvc并移除。 在web上找不到足够的资源。有什么想法吗

有人知道什么可能是正确的属性吗

这是列出所有pvc的脚本版本:

from kubernetes import client, config

config.load_kube_config()

v1 = client.CoreV1Api()

pvcs = v1.list_persistent_volume_claim_for_all_namespaces(watch=False)
print("---- PVCs ---")
print("%-16s\t%-40s\t%-6s" % ("Name", "Volume", "Size"))
for pvc in pvcs.items:
    print("%-16s\t%-40s\t%-6s" %
            (pvc.metadata.name, pvc.spec.volume_name,    
            pvc.spec.resources.requests['storage']))

编辑:
目前的解决方案:

from kubernetes import client, config, watch
from datetime import datetime, timezone, timedelta
import os, subprocess

#----------------------------------------------------
now = datetime.utcnow()
only_date = now.date()
print (" ")
print ("Today's date is:", (only_date))
print (" ")
retention_days = 0
#------------------------------------------------------

ns = os.getenv("K8S_NAMESPACE")
if ns is None:
    ns = "foo" # Namespace foo is aleady existing, or enter namespace

config.load_kube_config()

v1 = client.CoreV1Api()

pvcs = v1.list_namespaced_persistent_volume_claim(namespace=ns, watch=False)
print("---- PVCs ---")
print("%-16s\t%-40s\t%-6s\t%-6s" % ("Name", "Volume", "Size", "Date_Created"))
for pvc in pvcs.items:
    print("%-16s\t%-40s\t%-6s\t%-6s" %
            (pvc.metadata.name, pvc.spec.volume_name,    
            pvc.spec.resources.requests['storage'], pvc.metadata.creation_timestamp.date()))
print("")
filtered_pvcs_date = pvc.metadata.creation_timestamp.date() 


if (only_date - filtered_pvcs_date) > timedelta(retention_days):
    print ("PVC is older than configured retention of %d days" % (retention_days))
    
    cmd = ('kubectl delete pvc' + " " + pvc.metadata.name + " " + '-n' + " " + ns)
    os.system(cmd) 
    
    
else:
    print ("PVC is younger than configured retention of %d days" % (retention_days))

Tags: nameimportclientconfigdateisdaysmetadata
1条回答
网友
1楼 · 发布于 2024-09-24 00:28:18

您可以使用metadata.creation_timestamp字段检查对象的创建时间:

pvcs = v1.list_persistent_volume_claim_for_all_namespaces(watch=False)

#filter out all pvcs that have been created before 2021-04-25 18:25:30+00:00 (UTC)
from datetime import datetime, timezone
filtered_pvcs = [pvc for pvc in pvcs.items if pvc.metadata.creation_timestamp > 
    datetime(2021, 4, 25, 18, 25, 30, 0, tzinfo=timezone.utc)]

for pvc in filtered_pvcs:
    print ...

相关问题 更多 >