kuberneteskubernetes-pod

How to set the value of mountPath in an env variable in kubernetes?


I used a configMap to store the mount path value, but when i call in my pod it doesn't work it seems that the mountPath property can not be assigned to an env variable.

here is my code :

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80
        env:
        - name: MOUNT_PATH
          valueFrom:
           configMapKeyRef:
            name: my-configMap
            key: MOUNT_PATH
        volumeMounts:
        - name: nginx-volume
          mountPath: $(MOUNT_PATH)
      volumes:
      - name: nginx-volume
        persistentVolumeClaim:
         claimName: my-pvc

     ---


apiVersion: v1
kind: ConfigMap
metadata:
  name: my-configMap
  namespace: default
data:
  MOUNT_PATH: "/opt/somepath"

Solution

  • I deployed it in my lab and It's not possible to dynamically define any parameter on a manifest while deploying something using kubectl.

    When you define a env variable it will be accessible only after the pod get deployed and you're referencing it before this happens. So when you apply the manifest you created, there is no $(MOUNT_PATH), it doesn't exist anywhere.

    When you do this what goes to the container is the information that it should mount the volume at literally $(MOUNT_PATH).

    # df -h | grep MOUNT
    tmpfs           3.3G  454M  2.9G  14% /$(MOUNT_PATH)
    

    You can achieve this programmatically by using a external tool as helm or kustomize as commented by @Burak Serdar.

    Using Helm you can define your mountPath on your values.yaml and use this variable in your manifest.

    Few useful links regarding helm:

    Helm Quickstart Guide An Introduction to Helm, the Package Manager for Kubernetes Using Helm and Kustomize to Build More Declarative Kubernetes Workloads