Kubernetes: use environment variable/ConfigMap in PersistentVolume host path

12/1/2020

Does anyone know if is it possible to use environment variable or ConfigMap in hostPath of PersistentVolume? Found that it's possible with Helm, envsubst etc. But I want to use only Kubernetes functions

I need to create a volume that will have a not static path.

Here is my 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"
-- OLA
configmap
kubernetes

1 Answer

12/1/2020

You can't do it natively, but a combination of a kubernetes Job that reads from a configmap can do that for you. We will create a Job with the proper RBAC permissions, this job uses kubectl image, reads the configmap, and passes it to the PV creation manifest.

Here are the manifests:

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
-- Shai Katz
Source: StackOverflow