Kubernetes Tip: How to refer one environment variable in another environment variable declaration?


In Kubernetes, one way to pass configurable data to containers is using environment variable. Below is a pod definition that uses two environment variables.

apiVersion: v1
kind: Pod
metadata:
  name: api
spec:
  containers:
    - image: com.shekhargulati/api
      name: api
      env:
        - name: DATABASE_NAME
          value: "mydb"
        - name: DATASOURCE_URL
          value: jdbc:mysql://mysql:3306/mydb      
      ports:
        - containerPort: 8080

As you can see in the above Pod definition, we are using database name mydb twice. Isn’t it will be awesome if we can use DATABASE_NAME in the DATASOURCE_URL?

Kubernetes supports this use case by providing $(VAR) syntax as shown below.

apiVersion: v1
kind: Pod
metadata:
  name: api
spec:
  containers:
    - image: com.shekhargulati/api
      name: api
      env:
        - name: DATABASE_NAME
          value: "mydb"
        - name: DATASOURCE_URL
          value: "jdbc:mysql://mysql:3306/$(DATABASE_NAME)"
      ports:
        - containerPort: 8080

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: