I would like to dynamically provision 3 persistent volumes for my system, which are all based on a storageClass
that I previously created. My v1 code does its job successfully.
v1:
apiVersion: v1
kind: PersistentVolume
metadata:
name: volume0
labels:
type: storage-one
spec:
storageClassName: storage-one
accessModes:
- ReadWriteMany
capacity:
storage: 2Gi
hostPath:
path: /somepath
type: "DirectoryOrCreate"
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: volume1
labels:
type: storage-one
spec:
storageClassName: storage-one
accessModes:
- ReadWriteMany
capacity:
storage: 2Gi
hostPath:
path: /somepath
type: "DirectoryOrCreate"
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: volume2
labels:
type: storage-one
spec:
storageClassName: storage-one
accessModes:
- ReadWriteMany
capacity:
storage: 2Gi
hostPath:
path: /somepath
type: "DirectoryOrCreate"
I would like to refactor this code, possibly with a template that k8s can recognize, as the only variable here is the metadata.name
. Is it possible?
Natively kubernetes does not recognize any templates. But you can use any templating engine before you pass this yaml to kubectl.
Common practice is to use helm which uses gotpl inside. https://helm.sh/docs/chart_template_guide/
Your example will look like:
{{ range .Values.volume_names }}
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: {{ . }}
labels:
type: storage-one
spec:
storageClassName: storage-one
accessModes:
- ReadWriteMany
capacity:
storage: 2Gi
hostPath:
path: /somepath
type: "DirectoryOrCreate"
{{ end }}
And values.yaml:
volume_names:
- volume_this
- volume_that
Generally you can do render_with_your_fav_engine_to_stdout | kubectl apply -f
using any engine.
UPD: Generate based on given len (this one was weird):
{{ range $k, $v := until (atoi .Values.numVolumes) }}
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: volume-{{ $v }}
labels:
type: storage-one
spec:
storageClassName: storage-one
accessModes:
- ReadWriteMany
capacity:
storage: 2Gi
hostPath:
path: /somepath
type: "DirectoryOrCreate"
{{ end }}
And values.yaml:
numVolumes: "3"