<p>I am new to Kubernetes, I am creating POD on run time to push data and after pushing and collecting data I am deleting POD.</p>
<p>For the processing of files I have connected SSD. and assigned its path as <strong>hostPath: /my-drive/example</strong> while creating POD. Now when i run my POD i can see the files in defined path.</p>
<p>But, Now I just wanted to delete files created by POD in a hostPath directory while deleting POD. is it possible?</p>
<p>My POD file looks like.</p>
<pre><code>apiVersion: v1
kind: Pod
metadata:
  name: pod-example
  labels:
    app: pod-example
spec:
  containers:
  - name: pod-example
    image: &quot;myimage.com/abcd:latest&quot;
    imagePullPolicy: Always
    workingDir: /pod-example
    env:
    volumeMounts:
    - name: &quot;my-drive&quot;
      mountPath: &quot;/my-drive&quot;
  volumes:
  - name: &quot;my-drive&quot;
    persistentVolumeReclaimPolicy: Recycle
    hostPath:
      path: /my-drive/example
  restartPolicy: Never
  imagePullSecrets:
  - name: regcred
  affinity:
    podAntiAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          matchExpressions:
          - key: &quot;kubernetes.io/hostname&quot;
            operator: In
            values:
            - my-node
        topologyKey: &quot;kubernetes.io/hostname&quot;
</code></pre>

Rog Boy
<p>You can achieve this by using <code>lifecycle</code> hooks in K8s. Under them, <code>preStop</code> hook can be used here since you need to do action when stopping the pod.</p>
<p>Check docs related to lifecycle hooks: <a href="https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/" rel="nofollow noreferrer">https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/</a></p>
<p>If you exact know the files or let's say a directory to delete, you can use <code>Exec</code> hook hanlder. Check the sample below that I've added for your reference.</p>
<pre><code>lifecycle:
  preStop:
    exec:
      command:
        - &quot;sh&quot;
        - &quot;-c&quot;
        - &gt;
          echo &quot;Deleting files in my-drive/example/to-be-deleted&quot; &gt; /proc/1/fd/1 # Add preStop hook's stdout to main process's stdout
          rm -r my-drive/example/to-be-deleted
</code></pre>
<p>P.S. According to your problem statement, you are not using the POD continuously it seems. If the task that you are looking is to execute periodically or not continuous, I would suggest you to select either K8s <code>CronJob</code> or <code>Job</code> rather a <code>POD</code>.
Make sure to have required user access inside the container to delete files/floders.</p>
