<p>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</p>
<p>I need to create a volume that will have a not static path.</p>
<p>Here is my PV:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: PersistentVolume
metadata:
  name: some-pv
  labels:
    type: local
spec:
  storageClassName: manual
  capacity:
    storage: 2Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: &quot;${PATH_FROM_ENV}/some-path&quot;
</code></pre>

OLA
<p>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.</p>
<p>Here are the manifests:</p>
<pre><code>apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  namespace: default
  name: pv-generator-role
rules:
- apiGroups: [&quot;&quot;] # &quot;&quot; indicates the core API group
  resources: [&quot;persistentvolumes&quot;]
  verbs: [&quot;create&quot;]
- apiGroups: [&quot;&quot;] # &quot;&quot; indicates the core API group
  resources: [&quot;configmaps&quot;]
  verbs: [&quot;get&quot;]
---
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
        - &quot;-c&quot;
        - |
          /bin/bash &lt;&lt;'EOF'
          cat &lt;&lt;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=&quot;{.data.path}&quot;)/some-path
          EOF
      restartPolicy: Never
  backoffLimit: 4
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: path-configmap
  namespace: default
data:
  path: /mypath
</code></pre>
