在一个.yaml中创建多个持久卷

时间:2019-04-11 18:56:22

标签: kubernetes

我想为我的系统动态配置3个持久卷,这些持久卷全部基于我先前创建的storageClass。我的v1代码成功完成了工作。

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"

我想用k8s可以识别的模板来重构此代码,因为这里唯一的变量是metadata.name。有可能吗?

1 个答案:

答案 0 :(得分:1)

本地kubernetes无法识别任何模板。但是,您可以在将此Yaml传递给kubectl之前使用任何模板引擎。

常见做法是在内部使用使用gotpl的头盔。 https://helm.sh/docs/chart_template_guide/

您的示例如下所示:

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

和values.yaml:

volume_names: 
- volume_this
- volume_that

通常,您可以使用任何引擎来render_with_your_fav_engine_to_stdout | kubectl apply -f

UPD:根据给定的len生成(这很奇怪):

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

和values.yaml:

numVolumes: "3"