Kubernetes:在 PersistentVolume 主机路径中使用环境 variable/ConfigMap

Kubernetes: use environment variable/ConfigMap in PersistentVolume host path

有谁知道是否可以在 PersistentVolume 的 hostPath 中使用环境变量或 ConfigMap?发现可以使用 Helm、envsubst 等。但我只想使用 Kubernetes 函数

我需要创建一个具有非静态路径的卷。

这是我的PV:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: some-pv
  labels:
    type: local
spec:
  storageClassName: manual
  capacity:
    storage: 2Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "${PATH_FROM_ENV}/some-path"

您无法在本机执行此操作,但从 configmap 读取的 kubernetes 作业的组合可以为您执行此操作。 我们将创建一个具有适当 RBAC 权限的作业,该作业使用 kubectl 图像,读取 configmap,并将其传递给 PV 创建清单。

清单如下:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  namespace: default
  name: pv-generator-role
rules:
- apiGroups: [""] # "" indicates the core API group
  resources: ["persistentvolumes"]
  verbs: ["create"]
- apiGroups: [""] # "" indicates the core API group
  resources: ["configmaps"]
  verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: pv-geneartor-role-binding
  namespace: default
subjects:
- kind: ServiceAccount
  name: pv-generator-sa
  namespace: default
roleRef:
  kind: ClusterRole
  name: pv-generator-role
  apiGroup: rbac.authorization.k8s.io
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: pv-generator-sa
---
apiVersion: batch/v1
kind: Job
metadata:
  name: pv-generator
spec:
  template:
    spec:
      serviceAccountName: pv-generator-sa
      containers:
      - name: kubectl
        image: bitnami/kubectl
        command: 
        - sh
        - "-c"
        - |
          /bin/bash <<'EOF'
          cat <<EOF | kubectl apply -f -
          apiVersion: v1
          kind: PersistentVolume
          metadata:
            name: some-pv
            labels:
              type: local
          spec:
            storageClassName: manual
            capacity:
              storage: 2Gi
            accessModes:
              - ReadWriteOnce
            hostPath:
              path: $(kubectl get cm path-configmap -ojsonpath="{.data.path}")/some-path
          EOF
      restartPolicy: Never
  backoffLimit: 4
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: path-configmap
  namespace: default
data:
  path: /mypath