humiliatedpenguin
humiliatedpenguin

Reputation: 245

When should I use envFrom for configmaps?

According to the Kubernetes docs K8s Docs as of v1.6 and later we are able to use:

envFrom:
  - configMapRef:
      name: <config-file>

To define all the configMaps data as container env variables. What is the use case for using this versus setting it as an env variable with the name and key:

env:
        # Define the environment variable
        - name: SPECIAL_LEVEL_KEY
          valueFrom:
            configMapKeyRef:
              # The ConfigMap containing the value you want to assign to SPECIAL_LEVEL_KEY
              name: special-config
              # Specify the key associated with the value
              key: special.how

Would you use the second example if you had multiple variables in the file but only wanted to pull out a single key=value pair? I am trying to understand different use cases for scenarios I may encounter on the CKAD exam.

Upvotes: 19

Views: 39783

Answers (1)

ITChap
ITChap

Reputation: 4742

I have used both and some of my deployments used tens of environment variables. It depends very much of your specifics and the way you manage your settings.

In general if you have specific configmaps for specific applications where your application uses all or most of the keys in the configmaps, then envFrom is obviously easier the use and maintain. When one of your teammate needs to add a new feature flag for example, simply adding it to the configmap is enough to enable it on all your deployments.

In an other hand, if you organize your configmaps more by theme or if multiple applications need specific keys from the same configmap, then configMapKeyRef is better. You will take only the keys you need in your application and ensure that nothing will be overwritten accidentally. The downside being that your teammate, in order to add the same feature flag, will now have to edit the configmap and the deployments.

Keep it mind that both options are not exclusive and you will probably end up using a mixture of both. For example something like this might make sense:

envFrom:
    # This might contain environment-wide settings. Like the domain name that your application uses or a production only feature flag.
  - configMapRef:
      name: production-settings
    # Here you could store all the settings of this specific application.
  - configMapRef:
      name: my-app-settings
env:
  # This might be a bucket shared by multiple applications. So you might want to keep it a different configmap and let each aplication pick the keys they need.
  - name: S3_BUCKET
    valueFrom:
      configMapKeyRef:
        name: s3-settings
        key: bucket

Upvotes: 39

Related Questions