Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kubernetes ConfigMap: import from file as many values instead of as one?

Tags:

kubernetes

Creating a new ConfigMap from a file:
kubernetes create configmap foo --from-file=foo

This is how the ConfigMap looks internally: kubernetes get configmaps foo -o yaml

apiVersion: v1
data:
  foo: |
    VAR1=value1
    VAR2=value2

Then, I use this ConfigMap to create a set of environment variables in the container:

apiVersion: v1
kind: Pod
metadata:
  labels:
    name: app
  name: app
spec:
  containers:
    - name: app-server
      image: app:latest
      ports:
        - containerPort: 3000
      envFrom:
      - configMapRef:
          name: foo
      command: ["/bin/bash", "-c", "printenv"]

When the container command runs, I see the following output for printenv:

foo=VAR1=value1
VAR2=value2

So, an echo $foo command in the pod returns:
VAR1=value1 VAR2=value2

According to the documentation for ConfigMap with --from-file, this is expected behaviour.

What would be a creative way (and the proper place) to somehow get the values of this file available to the pod as individual env variables VAR1, VAR2, VAR3, etc. ?

like image 660
changingrainbows Avatar asked Oct 17 '22 14:10

changingrainbows


1 Answers

This is not possible with the current version (1.6.x) of Kubernetes. As written in the offical documentation for kubectl create configmap:

--from-file: Key file can be specified using its file path, in which case file basename will be used as configmap key, or optionally with a key and file path, in which case the given key will be used. Specifying a directory will iterate each named file in the directory whose basename is a valid configmap key.

When you want to create a configmap which is used like this, as input for the envFrom container configuration you could create it with the --from-literal option like this:

kubectl create configmap foo --from-literal=var1=value1 --from-literal=var2=value2

To still keep the file, you could transform your file into somethings which then runs this command like this:

eval "kubectl create configmap foo $(cat foo.txt | sed -e 's/^/--from-literal=/' | tr "\n" ' ')"

Along with that maybe checking the outstanding proposals like the --flatten flag proposal on Github are worth your time.

Also keep an eye on the variable naming. iirc VAR1 and VAR2 are not valid property names - they have to be lower case which might cause some issues when passing them on.

like image 69
pagid Avatar answered Nov 15 '22 08:11

pagid