How do I load a configMap in to an environment variable?

10/12/2018

How do I load a configMap into an environment variable?

Things I've done

Kubernetes documentation describes just this scenario, and following it:

I've actually set up my configMap through Terraform with this:

resource "kubernetes_config_map" "production_database_host" {
  metadata {
    name = "production-database-host"
  }

  data {
    connection_name = "${google_sql_database_instance.master.connection_name}"
  }
}

But via Kubernetes, it would look like this:

apiVersion: v1
data:
  connection_name: this_string_is_redacted
kind: ConfigMap
metadata:
  creationTimestamp: 2018-10-12T05:49:49Z
  name: production-database-host
  namespace: default
  resourceVersion: "316273"
  selfLink: /api/v1/namespaces/default/configmaps/production-database-host
  uid: a1c06423-cde2-11e8-b615-42010a800235

(Fetched by running kubectl get configmap production-database-host -o yaml)

Now, I also have a working container, in a deployment, where I added an environment variable like so:

env:
 - name: INSTANCE_CONNECTION_NAME
   valueFrom:
     configMapKeyRef:
       name: production-database-host
       key: connection_name

However, applying this config gives me:

$ kubectl apply -f .

error: error converting YAML to JSON: yaml: line 39: did not find expected key

What am I doing wrong here? Why won't this simply load this_string_is_redacted into the INSTANCE_CONNECTION_NAME environment variable?

Edit: All the source for my infrastructure is in this repo. The Terraform files are applied first, they create the Kubnernetes cluster and add the configMap. Then I apply the Kubernetes config.

-- Amin Shah Gilani
kubernetes

1 Answer

10/12/2018

It was a formatting issue, unfortunately the block:

env:
 - name: INSTANCE_CONNECTION_NAME
   valueFrom:
     configMapKeyRef:
       name: production-database-host
       key: connection_name

Was indented one space more than I should have been. Everything else works fine.

-- Amin Shah Gilani
Source: StackOverflow