Volume mounted configmap, by label selector

4/18/2018

I'm looking for a way to mount configs based on label selector.

I will have new configmap's created over time, which I will label with "intendeedtarget"="MainApp". The configs are created from json file, with filename as key.

E.g. a yml something like this (but working):

    volumeMounts:
      - name: appconfigs
        mountPath: /appconfigs
  volumes:
  - name: appconfigs
    configMap:
      selector:
        matchLabels:
          intendeedtarget: MainApp

That is new configs will be auto mounted in the running pods for the "MainApp" over time.

I have already gotten it to mount individual configs as files in the running pods with:

containers:
      - name: {{Name}}
        image: {{Image}}
        ports:
        - containerPort: 80
        volumeMounts:
          - name: appconfigs
            mountPath: /appconfigs
      volumes:
      - name: appconfigs
        configMap:
          name: {{ConfigName}}

This mounts the json applied to the configmap, as a separate file in the /appconfigs folder.

My goal now is to mount all configmaps with the label "intendeedtarget" = "MainApp" in /appconfigs.

Any suggestions?

A bonus question, does anyone know how to label a configmap as one command, i.e. when creating the configmap?

BR

-- Petter T
kubernetes

1 Answer

4/18/2018

So the short version is no, one cannot specify a whole range of volumeMounts, but there is a work-around available to you: initContainers:

I believe it would work like this:

  1. The Pod would declare a volume of type emptyDir, named appconfigs (just to make discussing it easy, the name isn't important) mounted where you wish. It is of type emptyDir because we only care about having some shared disk space between the initContainer and the "main" containers, and that shared space should evaporate when the Pod does
  2. The initContainer would either have a kubectl binary in it, or download one, or use one of the many, many kubernetes api client libraries, or even just a copy of curl in it
    1. using the ServiceAccount token, it queries for the ConfigMaps of your choosing. It is absolutely possible to put the label criteria into an environment variable of the initContainer, or the initContainer can even use the metadata of its own Pod for introspection, if you prefer that
    2. It extracts their payloads, massages them as you wish, and writes the files into the mount point of appconfigs
  3. Now the containers: will start, but it will find the config files in the shared volume mount, just as you specified
-- mdaniel
Source: StackOverflow