Scale statefulset based on latest volumeSnapshot

501 views Asked by At

If anyone know solutions please help me how I can do this.
I have “statefulset” which has following “volumeClaimTemplates” inside:
When I scale my replica count:
“kubectl scale statefulset --replicas=2 my-statefulset”
new “PVC” create from “volumesnapshot” object which name = “MySnapshot”

  volumeClaimTemplates:
  - apiVersion: v1
    kind: PersistentVolumeClaim
    metadata:
      name: data
    spec:
      accessModes:
      - ReadWriteOnce
      dataSource:
        apiGroup: snapshot.storage.k8s.io
        kind: VolumeSnapshot
        name: MySnapshot
      resources:
        requests:
          storage: 800Gi
      storageClassName: ebs-sc
      volumeMode: Filesystem

My question:
Is it possible to use dynamic name in field

volumeClaimTemplates:
  dataSource:
    apiGroup: snapshot.storage.k8s.io
    kind: VolumeSnapshot
    name: ?  

Clarify:
When new snapshot created, modify statefulset and set volumeClaimTemplates.dataSource.name = new-name
Why I need this:
I have cronjob which automatically create snapshot with new name ex: MySnapshot_1, MySnapshot_2 … And I need latest data into my “PVC” when new replica is created .

1

There are 1 answers

1
Nariman Maad On

https://kyverno.io/ Can do this Job

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: mutate-pvc
spec:
  rules:
    - name: set-name-latest-snapshot
      match:
        any:
        - resources:
            kinds:
            - PersistentVolumeClaim
      context:
      - name: latestSnapshotTime
        apiCall:
          urlPath: "/apis/snapshot.storage.k8s.io/v1/namespaces/{{request.namespace}}/volumesnapshots"
          jmesPath: "items[?status.readyToUse].status.creationTime | sort(@)[-1]" 
      - name: latestSnapshotName
        apiCall:
          urlPath: "/apis/snapshot.storage.k8s.io/v1/namespaces/{{request.namespace}}/volumesnapshots"
          jmesPath: "items[?status.creationTime == '{{latestSnapshotTime}}'][].metadata.name | [0]"
      mutate:
        patchStrategicMerge: 
          spec:
            dataSource:
              name: "{{latestSnapshotName}}"