如何在 20 天后自动自毁 Kubernetes pod?

How can I self-destruct a Kubernetes pod automatically after 20 days?

我需要设置一个 kubernetes pod 来为我的 Web 应用程序的客户端创建演示环境,试用期为 20 天。过了这20天,pod应该会自动删除,请问如何让pod在20天后自毁呢? 我使用 Rancher 来部署我的 pods.

您可以使用两种方式实现此目的,编写您自己的代码并在 K8s 上运行检查状态,这将在 20 天后删除部署 (POD)

参考 github : https://github.com/dignajar/clean-pods

您的广告连播没有获取 auto-deleted 的选项。

要么你 运行 cronjob 间隔 20 哪个将删除特定的部署,但在这种情况下你必须再次 pass 部署或 pod name 所以 cronjob 有那个变量。

示例:1

使用delete_namespaced_pod

    from kubernetes import client, config
    from kubernetes.client.rest import ApiException
    config.load_incluster_config() # if running inside k8s cluster config.load_kube_config()
    
    configuration = client.Configuration()
    
    with client.ApiClient(configuration) as api_client:
        api_instance = client.CoreV1Api(api_client)
        
        namespace = '<Namespace name>'
        name = '<POD name>'  
api_instance.list_namespaced_pod(namespace)
        
        try:
            api_response = api_instance.delete_namespaced_pod(name, namespace)
            print(api_response)
        except ApiException as e:
            print("Exception when calling CoreV1Api->delete_namespaced_pod: %s\n" % e) 

示例:2

定时任务

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: cleanup
spec:
  schedule: "30 1 1,20 * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: kubectl-container
            image: bitnami/kubectl:latest
            command: ["sh", "-c", "kubectl delete pod <POD name or add variable here>"]
          restartPolicy: Never

额外

你也可以写shell脚本其中运行daily运行几个命令检查 PODAGE,如果等于 20

,则删除
kubectl get pods --field-selector=status.phase=Pending --sort-by=.metadata.creationTimestamp | awk 'match(,/[20-9]d|[0-9][0-9]d|[0-9][0-9][0-9]d/) {print [=12=]}'

更新

如果您遇到任何禁止的错误,请创建服务帐户并将其与 cronjob 一起使用

apiVersion: v1
kind: ServiceAccount
metadata:
  name: sa-name
  namespace: default

---
 
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: default
  name: sa-role
rules:
- apiGroups: ["*"]
  resources: ["*"]
  verbs: ["list", "delete"]

---

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: sa-rolebinding
  namespace: default
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: sa-role
subjects:
- kind: ServiceAccount
  name: sa-name
  namespace: default

---

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: jobs
spec:
  schedule: "*/30 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          serviceAccountName: sa-role