Kubernetes Pods: Use environment variables to define arguments

kubernetes pod argument command environment variable

2 min read | by Jordi Prats

When configuring command line arguments for containers we might need to be able to use certain values that might be elsewhere like the name of the current namespace.

We can use environment variables as the source of the information without having to write a wrappet to actually populate them

To do so we'll have to use the $() syntax, pleace notice how it's using parentheses instead of curly braces that you might be more familar. Then we just need to define the environment variable with whatever value we need. In this example we are using valueFrom to get the object's namespace:

kind: Deployment
apiVersion: apps/v1
metadata:
  name: test-env
  labels:
    app: test-env
spec:
  selector:
    matchLabels:
      app: test-env
  replicas: 1
  strategy:
    type: RollingUpdate
  template:
    metadata:
      labels:
        app: test-env
    spec:
      containers:
      - name: test-env
        image: alpine:latest
        imagePullPolicy: Always
        command:  ["echo"]
        args:
        - namespace=$(CURRENT_NAMESPACE)
        env:
        - name: CURRENT_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace

Once we apply it we will be able to see how the value have been populated:

$ kubectl apply -f test_env.yaml
deployment.apps/test-env created
$ kubectl get pods
NAME                       READY   STATUS              RESTARTS   AGE
test-env-9499cdd8c-7jwsd   0/1     ContainerCreating   0          5s
$ kubectl logs test-env-9499cdd8c-7jwsd
namespace=test-pet2cattle

We can use this not only on a Deployment as we did on the example, but on any Pod template we need.


Posted on 26/08/2022