Dead Simple: Include Env. Variables in Kubernetes Deployment (YAML)
This week I found myself needing to parameterize Kubernetes (k8s) yaml files. The internet had a ton of information on the subject, too much infact… it was information overload. I wasn’t ready to adopt special tools like kustomize or helm. Ultimately I settled on the following approach which expands on one of the many answers on this SO post.
The process itself is very simple: add placeholders for env. variables in yaml and then substitute/replace them before running kubectl apply
Step 0: Install envsubst
We’ll use a small substitution package called envsubst
to make our lives easier. To install: apt-getg y install getext-base
, or for other distros see installation steps here.
Step 1: Parameterize YAML file
Add parameters to a k8s manifest using the following ${} syntax as shown below. This is a partial deployment and these variables can be used anywhere — I just happened to pick “namespace” as my variable of interest.
#mydeploy.yamlapiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: myapp
name: myapp
namespace: ${K8S_NAMESPACE} # <---
spec:
replicas: 1
...
Note both${K8S_NAMESPACE}
and $K8S_NAMESPACE
are valid syntax (bash shit)
Step 2: Export env variables
export K8S_NAMESPACE="uat"
Step 3: Kubectly apply with substitution
Instead of kubectl apply -f mydeploy.yaml
the command becomes:
envsubst < mydeploy.yaml | kubectl apply -f -
and viola