English

Share with friends

Note

In this guide, we will talk about how to create and use Kubernetes environment variables - how to define them, access them, override them, K8s env variable best practices, and more.

A Complete Guide to Kubernetes (K8s) Environment Variables cover image

Kubernetes is such a powerful platform that it not only simplifies the deployment and management of containerized applications but also offers features that make it incredibly flexible. Among these features, Kubernetes environment variables are pivotal in configuring and customizing your applications within containers.

In this blog post, you will dive into Kubernetes environment variables, demystifying their importance, and exploring how they empower developers and operators alike.

Whether you're new to Kubernetes or a seasoned pro, understanding the ins and outs of environment variables in this context is crucial for harnessing the full potential of containerization.

Let's embark on this journey to unravel the secrets of Kubernetes environment variables together!

What are Kubernetes Environment Variables?

Environment variables in Kubernetes are a fundamental concept that allows you to configure and customize applications running inside containers. They are key-value pairs containing information that applications can use to adjust their behavior at runtime.

These variables are injected into the container's environment and can be used to pass configuration data, secrets, or any other dynamic information required by the application.

Let's see how these work in Kubernetes.

Defining Environment Variables

Environment variables can be defined in Kubernetes in several ways. Here are a few of them.

1. In Kubernetes YAML Manifests: You can specify environment variables directly in your pod or container specifications in the YAML manifest files.

For example:

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
    - name: my-container
      image: my-app-image
      env:
        - name: DATABASE_URL
          value: "mysql://user:password@db-host:3306/database"

2. Using ConfigMaps and Secrets: Kubernetes allows you to store environment variables in ConfigMaps (for non-sensitive data) and Secrets (for sensitive data) and then reference them in your pod specifications.

This approach makes it easier to manage and update configuration data separately from your application code.

Also Read: 13 Configurations Options for NGNIX Ingress

Accessing Environment Variables

Once defined, environment variables are accessible within your containerized application just like any other environment variable.

You can read them using the programming language or framework-specific methods provided by your application stack.

For example, in a Node.js application, you can access an environment variable like this:

const databaseUrl = process.env.DATABASE_URL;

Benefits of Environment Variables

Environment variables in Kubernetes offer several advantages:

  1. Separation of Configuration: Storing configuration data separately from your application code simplifies management and allows you to change configuration without modifying the application's source code.

  2. Security: Sensitive data can be stored in Secrets, which are encrypted, ensuring that sensitive information like database passwords is not exposed in plain text in your configuration files.

  3. Portability: Environment variables make it easy to move your application between different environments (e.g., development, testing, production)without code changes, as you can adjust the environment variables for each Kubernetes environment.

Also Read: How to Keep Docker Container Running?

Dynamic Updates

Kubernetes allows you to update environment variables dynamically. You can modify ConfigMaps or Secrets, and Kubernetes will automatically propagate changes to the running pods that reference them.

Kubernetes environment variables are a powerful tool for configuring and customizing containerized applications, offering flexibility, security, and ease of management.

They enable you to keep your application code clean and portable while efficiently handling various configurations and secrets.

Let's create a Kubernetes Environment Variable and understand its structure!

Also Read: How to Create and Use KubeConfig File?

How to Create a Kubernetes Environment Variable?

In Kubernetes, you can define environment variables for your containers in your pod or deployment specifications using the following syntax:

apiVersion: <apiVersion>
kind: <Kind>
metadata:
  name: <ResourceName>
spec:
  containers:
    - name: <ContainerName>
      image: <ContainerImage>
      env:
        - name: VARIABLE_NAME_1
          value: VARIABLE_VALUE_1
        - name: VARIABLE_NAME_2
          value: VARIABLE_VALUE_2

Here's a breakdown of the syntax:

  • <apiVersion>: The API version of the Kubernetes resource being defined.

  • <Kind>: The kind of Kubernetes resource (e.g., Pod, Deployment, Job, etc.).

  • <ResourceName>: A unique name for the Kubernetes resource

  • <ContainerName>: The name of the container within the pod

  • <ContainerImage>: The Docker image used for the container.

Inside the containers section, you define the environment variables using the env field.

Each environment variable is defined as a YAML list item with two attributes:

  • name: The name of the environment variable.

  • value: The value of the environment variable.

You can specify as many environment variables as needed, each represented by a separate - name and - value pair.

Here's an example:

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
    - name: my-container
      image: my-app-image
      env:
        - name: DATABASE_URL
          value: "mysql://user:password@db-host:3306/database"
        - name: API_KEY
          value: "your-api-key"

In this example, you have defined two environment variables, DATABASE_URL and API_KEY, with their respective values.

Remember that Kubernetes environment variables can also be sourced from ConfigMaps or Secrets using the valueFrom field, which allows you to reference external configuration data.

This provides more flexibility and security for managing your application's configuration within the Kubernetes cluster.

Setting environment variables in Kubernetes can be done in several ways, including using the env field directly in your pod or deployment specifications and by referencing ConfigMaps.

Also Read: When to Use Kubectl Delete Deployment?

Setting Environment Variables using the env Field

You can set environment variables directly in your pod or deployment specifications using the env field.

Here's an example of how to do it. The below snippet adds Environment Variables to a Pod.

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
    - name: my-container
      image: my-app-image
      env:
        - name: DATABASE_URL
          value: "mysql://user:password@db-host:3306/database"
        - name: API_KEY
          value: "your-api-key"

In this example, we define two environment variables, DATABASE_URL and API_KEY, directly within the pod specification for the my-container container.

Using ConfigMaps to Set Environment Variables

A more organized and scalable approach for managing environment variables in Kubernetes is to use ConfigMaps.

ConfigMaps allows you to store configuration data separately from your pod or deployment specifications. Here's how to set environment variables using ConfigMaps:

Define a ConfigMap

Create a ConfigMap that contains your environment variables:

apiVersion: v1
kind: ConfigMap
metadata:
  name: my-config
data:
  DATABASE_URL: "mysql://user:password@db-host:3306/database"
  API_KEY: "your-api-key"

Reference the ConfigMap in a Pod or Deployment

Now, you can reference the ConfigMap in your pod or deployment specifications using the envFrom field.

Here's how.

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
    - name: my-container
      image: my-app-image
      envFrom:
        - configMapRef:
            name: my-config

This approach allows you to centralize your configuration data in ConfigMaps, making it easier to update and manage environment variables across multiple pods or deployments.

If you need to change a variable, you only need to update the ConfigMap, and Kubernetes will automatically propagate the changes to the pods that reference it.

How to Override Environment Variables in Kubernetes?

In Kubernetes, you can override environment variables set in a pod or deployment by providing new values in a few different ways.

Here are three common methods for overriding environment variables.

1. Override Environment Variables in the Deployment YAML

You can directly modify the YAML file of your deployment to update the environment variables. Simply edit the deployment configuration and change the values in the env field.

After making these changes, you can apply the updated YAML file to your cluster using kubectl apply -f deployment.yaml.

Kubernetes will update the existing pods with the new environment variable values.

Also Read: How to Use Terraform Apply Command?

2. Using ConfigMaps

If you're using ConfigMaps to manage your environment variables, you can update the values in the ConfigMap itself.

After updating the ConfigMap, Kubernetes will automatically propagate the changes to all pods that reference it.

3. Using Secrets

For sensitive data stored in Secrets, you can update the secret data directly.

Here's an example:

apiVersion: v1
kind: Secret
metadata:
  name: my-secret
data:
  DATABASE_PASSWORD: base64-encoded-new-password

After updating the secret, any pods that use this secret will automatically receive the updated value. Note that secrets should be base64-encoded.

Remember that Kubernetes handles the propagation of changes to pods when you update ConfigMaps or Secrets.

It may take a moment for the updates to be reflected in the running pods, as Kubernetes needs to recreate or restart them with the new values.

Using any of these methods, you can easily override environment variables in Kubernetes to update configuration data, secrets, or any other dynamic information without the need to modify the application code or recreate the entire deployment.

Also Read: How to Use Kubectl Rollout Restart?

Best Practices of Using Environment Variables in Kubernetes

Using environment variables in Kubernetes effectively is crucial for maintaining a well-organized and secure containerized environment.

Here are some best practices for using environment variables in Kubernetes.

1. Use ConfigMaps and Secrets:

Store configuration data in ConfigMaps and sensitive information in Secrets. This separation makes it easier to manage and update configurations and secrets independently.

2. Avoid Hardcoding Values

Do not hardcode environment variable values directly into pod or deployment specifications. Instead, use ConfigMaps and Secrets to store these values, making your configuration more maintainable and secure.

3. Limit Sensitive Data in Environment Variables

Avoid storing sensitive information, such as passwords or API keys, directly in environment variables. Use Kubernetes Secrets for these types of data. When you need to use them in environment variables, reference the Secrets.

Also Read: Kubernetes Cost Optimization Best Practices

4. Use Descriptive Names

Give your environment variables meaningful names. This makes it easier for others to understand their purpose and helps with maintenance.

5. Version Control Configurations

Store your ConfigMaps and Secrets definitions in version control systems (e.g., Git) to track changes and collaborate with your team.

6. Immutable Containers

Design your containers to be immutable, meaning they should not change configuration at runtime. Instead, create new container images with updated configurations and redeploy them.

7. Keep Configuration Simple

Avoid overloading containers with excessive environment variables. Keep the configuration minimal and focused on what's necessary for the application to run.

8. Use Environment Variables for Dynamic Configuration

Use environment variables for dynamic configuration aspects like connecting to databases, API endpoints, or adjusting application behavior based on the environment (e.g., development, testing, production).

9. Implement Configuration Validation

Validate environment variables within your application to ensure they have the expected format and values, reducing the risk of misconfigurations.

10. Avoid Secrets in Environment Variables

Never store sensitive data directly in environment variables. If you must use sensitive data in environment variables, use Kubernetes Secrets and then reference them.

With this you have reached the end of the blog, let's end it with a conclusion.

Summary of Kubernetes Environment Variables

To summarise it all, you started by understanding what environmental variables are and how they work, delving into the syntax for defining them.

You learned to set these variables directly in pods and deployments or through ConfigMaps for cleaner, more organized management.

To harness their power, you explored real-world examples and saw how to access them within pods. When changes were needed, you discovered methods to override variables seamlessly.

But you didn't stop there.

You embraced best practices, like keeping secrets safe in Kubernetes Secrets and ensuring version control for ConfigMaps and Secrets.

In this journey, you've gained the knowledge to configure and manage Kubernetes Environment Variables effectively, unlocking the full potential of containerized applications.

Share with friends

Priyansh Khodiyar's profile

Written by Priyansh Khodiyar

Priyansh is the founder of UnYAML and a software engineer with a passion for writing. He has good experience with writing and working around DevOps tools and technologies, APMs, Kubernetes APIs, etc and loves to share his knowledge with others.

Further Reading

Life is better with cookies 🍪

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt out if you wish. Cookie Policy