How to run a command on PersistentVolume creation?

5/25/2020

I have a StatefulSet which looks like this

apiVersion: v1
kind: StatefulSet
metadata:
  name: web
spec:
  ...
  volumeClaimTemplates:
metadata:
      name: www
    spec:
      resources:
        requests:
          storage: 1Gi

It will create a PersistentVolumeClaim (PVC) and a PersistentVolume (PV) for each Pod of a Service it controls.

I want to execute some commands on those PVs before the Pod creation.

I was thinking to create a Job which mounts those PVs and runs the commands but how do I know how many of PVs were created?

Is there a kubernetes-native solution to trigger some pod execution on PV creation?

-- LEQADA
kubernetes
kubernetes-statefulset
persistent-volumes

1 Answer

5/25/2020

The solution is InitContianer.

You can add it to a spec of your StatufulSet:

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name:  web
spec:
...
  spec:
    initContainers:
    - name: init-myapp
      image: ubuntu:latest
      command:
      - bash
      - "-c"
      - "your command"
      volumeMounts:
      - name: yourvolume
        mountPath: /mnt/myvolume
-- Anton Kostenko
Source: StackOverflow