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

2/15/2022

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.

-- Luis Manuel Cortés Tirado
demo
kubernetes
kubernetes-pod
rancher

1 Answer

2/15/2022

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}'

Update

If you face any error for forbidden do create the service account and use that with 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
-- Harsh Manvar
Source: StackOverflow