首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用python API按年龄过滤列出kubernetes持久化卷声明

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

Stack Overflow用户
提问于 2021-04-25 03:24:49
回答 1查看 352关注 0票数 1

我正在寻找kubernetes pvc,这是旧于一定的时间限制和删除。在web上找不到足够的资源。有什么想法吗?

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

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

代码语言:javascript
复制
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']))

编辑:

目前的解决方案:

代码语言:javascript
复制
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))
EN

回答 1

Stack Overflow用户

发布于 2021-04-26 02:49:43

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

代码语言:javascript
复制
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 ...
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67246637

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档