Kubernetes: Mount multiple volumes into the same directory

We often need to mount multiple volumes into the same directory. For example, we need to mount SSL Certificate and Key into the same directory. However, the typical syntax of volumeMount would fail. To do this, projected volume needs to be used. Here is an example:

Create Two secrets, we will be mounting them later in the post.

kubectl create secret generic  secret-1 --from-literal=key1=123
secret/secret-1 created
kubectl create secret generic  secret-2 --from-literal=key2=abc
secret/secret-2 created

# Validate the values

kubectl get secrets secret-1  -ogo-template='{{ .data.key1 |base64decode}}{{"\n"}}'
123

kubectl get secrets secret-2  -ogo-template='{{ .data.key2 |base64decode}}{{"\n"}}'
abc

Create a Pod and “try” to mount the two secrets as volume into the same directory.

apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: my-pod
  name: my-pod
spec:
  volumes:
  - name: secret-vol-1
    secret:
      secretName: secret-1
      optional: false
  - name: secret-vol-2
    secret:
      secretName: secret-2
      optional: false

  containers:
  - image: nginx
    name: my-pod
    resources: {}
    volumeMounts:
    - name: secret-vol-1
      mountPath: /var/secret-data
    - name: secret-vol-2
      mountPath: /var/secret-data
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}

The above manifest file will lead to a “must be unique” error.

kubectl create  -f p.yml
The Pod "my-pod" is invalid: spec.containers[0].volumeMounts[1].mountPath: Invalid value: "/var/secret-data": must be unique

Solution:

Using the projected volume, we can mount multiple volumes into a common directory. Here is an example manifest file.

apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: my-pod
  name: my-pod
spec:
  volumes:
  - name: all-in-one
    projected:
      sources:
      - secret:
          name: secret-1
          items:
            - key: key1
              path: file-1
      - secret:
          name: secret-2
          items:
            - key: key2
              path: file-2
              mode: 511
  containers:
  - image: nginx
    name: my-pod
    resources: {}
    volumeMounts:
    - name: all-in-one
      mountPath: /var/secret-data
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}
kubectl exec -it my-pod  -- bash
root@my-pod:/# ls -lrt /var/secret-data/
total 0
lrwxrwxrwx 1 root root 13 Jan 23 22:45 file-2 -> ..data/file-2
lrwxrwxrwx 1 root root 13 Jan 23 22:45 file-1 -> ..data/file-1
root@my-pod:/#
root@my-pod:/# cat /var/secret-data/file-1
123
root@my-pod:/#
root@my-pod:/#
root@my-pod:/#
root@my-pod:/# cat /var/secret-data/file-2
abc
root@my-pod:/#
Reference:
  • https://kubernetes.io/docs/concepts/storage/projected-volumes/
5 1 vote
Please, Rate this post
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Scroll to Top