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

Time:02-16

I need to set up a kubernetes pod to create demo environments for clients of my web application, with a 20 day trial duration. After these 20 days, the pod should be automatically deleted, how can I make the pod self-destruct after 20 days? I use Rancher to deploy my pods.

CodePudding user response:

You can achieve this using two ways, write your own code and run on K8s to check status which will delete the deployment (POD) after 20 days

Reference github : https://github.com/dignajar/clean-pods

There is no option for your pod to get auto-deleted.

Either you run cronjob at an interval of 20 days which will delete specific deployment but again in this case you have to pass deployment or pod name so cronjob has that variable.

Example : 1

use 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) 

Example : 2

cronjob

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

Extra

You can also write shell script which run daily run few command to check the AGE of POD and delete if equal to 20 days

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

CodePudding user response:

@Harsh Manvar I have been testing with an Nginx deployment, but when I create the CronJob I get errors and the nginx deployment is not deleted.

cat deployment.yaml

apiVersion: v1
kind: Service
metadata:
  name: httpd-service-dev
  labels:
    app: httpd_app_dev
spec:
  type: NodePort
  selector:
    app: httpd_app_dev
  ports:
    - port: 80
      targetPort: 80
      nodePort: 30005

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: httpd-deployment-dev
  labels:
    app: httpd_app_dev
spec:
  replicas: 2
  selector:
    matchLabels:
      app: httpd_app_dev
  template:
    metadata:
      labels:
        app: httpd_app_dev
    spec:
      containers:
        - name: httpd-container-dev
          image: httpd:latest
          ports:
            - containerPort: 80
---
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: cleanup
spec:
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: kubectl-container
            image: bitnami/kubectl:latest
            command: ["sh", "-c", "kubectl delete deployment httpd-deployment-dev", "kubectl delete service httpd-service-dev"]
          restartPolicy: Never

kubectl apply -f deployment.yaml

service/httpd-service-dev created
deployment.apps/httpd-deployment-dev created
Warning: batch/v1beta1 CronJob is deprecated in v1.21 , unavailable in v1.25 ; use batch/v1 CronJob
cronjob.batch/cleanup created

kubectl get all

<pre>NAME                                        READY   STATUS              RESTARTS   AGE
pod/cleanup-27415557-7fzs5                  0/1     Error               0          68s
pod/cleanup-27415557-dfqvz                  0/1     Error               0          80s
pod/cleanup-27415557-gdcc4                  0/1     Error               0          83s
pod/cleanup-27415557-h2xt9                  0/1     Error               0          74s
pod/cleanup-27415557-mjxwg                  0/1     Error               0          64s
pod/cleanup-27415557-pwwr8                  0/1     Error               0          71s
pod/cleanup-27415557-rc4mq                  0/1     Error               0          77s
pod/cleanup-27415558-bzxn4                  0/1     Error               0          9s
pod/cleanup-27415558-hf5pj                  0/1     Error               0          23s
pod/cleanup-27415558-lmlkc                  0/1     ContainerCreating   0          3s
pod/cleanup-27415558-nr28h                  0/1     Error               0          19s
pod/cleanup-27415558-vhlrl                  0/1     Error               0          16s
pod/cleanup-27415558-vxt2v                  0/1     Error               0          12s
pod/cleanup-27415558-x8wv4                  0/1     Error               0          6s
pod/httpd-deployment-dev-697fb85b68-4csv8   1/1     Running             0          20m
pod/httpd-deployment-dev-697fb85b68-v8752   1/1     Running             0          20m

NAME                        TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
service/httpd-service-dev   NodePort    10.104.225.20   &lt;none&gt;        80:30005/TCP   20m
service/kubernetes          ClusterIP   10.96.0.1       &lt;none&gt;        443/TCP        40m

NAME                                   READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/httpd-deployment-dev   2/2     2            2           20m

NAME                                              DESIRED   CURRENT   READY   AGE
replicaset.apps/httpd-deployment-dev-697fb85b68   2         2         2       20m

NAME                    SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
cronjob.batch/cleanup   */1 * * * *   False     1        23s             20m

NAME                         COMPLETIONS   DURATION   AGE
job.batch/cleanup-27415557   0/1           83s        83s
job.batch/cleanup-27415558   0/1           23s        23s
</pre>
  • Related