Sarabesh n.r
Sarabesh n.r

Reputation: 73

Is there any way to use configMaps in K8s with nested values to be used as environment variable in the pod?

I have the sample cm.yml for configMap with nested json like data.

kind: ConfigMap
metadata:
 name: sample-cm
data:
 spring: |-
  rabbitmq: |-
   host: "sample.com"
  datasource: |-
   url: "jdbc:postgresql:sampleDb"

I have to set environment variables, spring-rabbitmq-host=sample.com and spring-datasource-url= jdbc:postgresql:sampleDb in the following pod.

kind: Pod
metadata:
 name: pod-sample
spec:
 containers:
  - name: test-container
    image: gcr.io/google_containers/busybox
    command: [ "/bin/sh", "-c", "env" ]
    env:
     - name: sping-rabbitmq-host
       valueFrom:
        configMapKeyRef:
         name: sample-cm    
         key: <what should i specify here?>
     - name: spring-datasource-url
       valueFrom:
        configMapKeyRef:
         name: sample-cm
         key: <what should i specify here?>

Upvotes: 5

Views: 6758

Answers (1)

kool
kool

Reputation: 3613

Unfortunately it won't be possible to pass values from the configmap you created as separate environment variables because it is read as a single string.

You can check it using kubectl describe cm sample-cm

Name:         sample-cm
Namespace:    default
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"v1","data":{"spring":"rabbitmq: |-\n host: \"sample.com\"\ndatasource: |-\n url: \"jdbc:postgresql:sampleDb\""},"kind":"Con...

Data
====
spring:
----
rabbitmq: |-
 host: "sample.com"
datasource: |-
 url: "jdbc:postgresql:sampleDb"
Events:  <none>

ConfigMap needs key-value pairs so you have to modify it to represent separate values.

Simplest approach would be:

apiVersion: v1
kind: ConfigMap
metadata:
 name: sample-cm
data:
   host: "sample.com"
   url: "jdbc:postgresql:sampleDb"

so the values will look like this:

kubectl describe cm sample-cm
Name:         sample-cm
Namespace:    default
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"v1","data":{"host":"sample.com","url":"jdbc:postgresql:sampleDb"},"kind":"ConfigMap","metadata":{"annotations":{},"name":"s...

Data
====
host:
----
sample.com
url:
----
jdbc:postgresql:sampleDb
Events:  <none>

and pass it to a pod:

apiVersion: v1
kind: Pod
metadata:
 name: pod
spec:
 containers:
  - name: test-container
    image: gcr.io/google_containers/busybox
    command: [ "/bin/sh", "-c", "env" ]
    env:
    - name: sping-rabbitmq-host
      valueFrom:
        configMapKeyRef:
          name: sample-cm
          key: host
    - name: spring-datasource-url
      valueFrom:
        configMapKeyRef:
          name: sample-cm
          key: url

Upvotes: 5

Related Questions