How Do I Set Default Environment Variables for Containers at Scale?
In this guide, we will demonstrate how to set default environment variables for Kubernetes containers at scale using Pulumi. This is particularly useful for configuring applications with common settings across multiple deployments.
We will create a Kubernetes deployment and configure environment variables for the containers in that deployment. The deployment will use a simple NGINX container as an example.
import * as pulumi from "@pulumi/pulumi";
import * as k8s from "@pulumi/kubernetes";
// Create a Kubernetes namespace
const ns = new k8s.core.v1.Namespace("example-namespace");
// Define the environment variables
const envVars = [
{ name: "ENV_VAR_1", value: "value1" },
{ name: "ENV_VAR_2", value: "value2" },
];
// Create a Kubernetes deployment
const deployment = new k8s.apps.v1.Deployment("nginx-deployment", {
metadata: {
namespace: ns.metadata.name,
},
spec: {
selector: { matchLabels: { app: "nginx" } },
replicas: 3,
template: {
metadata: {
labels: { app: "nginx" },
},
spec: {
containers: [
{
name: "nginx",
image: "nginx:1.21.6",
ports: [{ containerPort: 80 }],
env: envVars, // Set environment variables here
},
],
},
},
},
});
// Export the namespace name
export const namespaceName = ns.metadata.name;
Key Points
- Namespace Creation: We create a Kubernetes namespace to logically group our resources.
- Environment Variables: We define an array of environment variables that will be applied to the containers.
- Deployment Configuration: We create a Kubernetes deployment that includes the environment variables in the container specification.
Summary
In this guide, we demonstrated how to set default environment variables for containers in a Kubernetes deployment using Pulumi. We created a namespace, defined environment variables, and applied them to the containers within a deployment. This approach allows for scalable and consistent configuration management across multiple deployments.
Deploy this code
Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.
Sign upNew to Pulumi?
Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.
Sign upThank you for your feedback!
If you have a question about how to use Pulumi, reach out in Community Slack.
Open an issue on GitHub to report a problem or suggest an improvement.