How to set Env from ConfigMap in kubectl run?

5/10/2020

for debug reasons I try to run a container (alpine) via kubectl run and set some Environment vars from ConfigMap or Secret. To do that I understood to use --override= parameter. But if I execute the Container and echo the vars nothing is set. Is my structure of my inline json wrong?

kubectl run --dry-run=client --restart=Never --image=alpine -n app-ns psql-demo --overrides='
{
    "apiVersion": "v1",
    "spec": {        
        "env": [
            {
                "name": "POSTGRES_HOST",
                "valueFrom": {
                    "configMapKeyRef": {
                        "key": "POSTGRES_HOST",
                        "name": "db-config"
                    }
                }
            }
        ]
    }
}' -o yaml -- sh

I try to check it via echo ${POSTGRES_HOST}.

The ConfigMap config here:

apiVersion: v1
data:
  POSTGRES_HOST: db.host.com
kind: ConfigMap
metadata:
  labels:
    component: postgres
  name: db-config
  namespace: app-ns

Any idea? Thanks a lot!

-- Gerrit
kubectl
kubernetes
kubernetes-pod

1 Answer

5/10/2020

The struct of your json is a bit off, it should be something like this:

{
  "spec": {
    "containers": {
      "env": [
        {
          "name": "POSTGRES_HOST",
          "valueFrom": {
            "configMapKeyRef": {
              "name": "db-config",
              "key": "POSTGRES_HOST"
            }
          }
        }
      ]
    }
  }
}

And note that the first "name" is the actual env variable name that will appear inside your container, it doesn't have to be identical to the actual key you used inside your configmap.

  • It's important to note that kubectl run ignores unknown fields.

To debug this, you can run the command you specified, and then in another terminal:

kubectl get pod POD_NAME -o json

From there you can see if the actual env specification structure differs from your json override value.

-- omricoco
Source: StackOverflow