Diego
Diego

Reputation: 35

Using a variable within a path in Kubernetes

I have a simple StatefulSet with two containers. I just want to share a path by an emptyDir volume:

volumes:
 - name: shared-folder
 emptyDir: {}

The first container is a busybox:

  - image: busybox
    name: test
    command:
      - sleep
      - "3600"
    volumeMounts:
    - mountPath: /cache
      name: shared-folder

The second container creates a file on /cache/<POD_NAME>. I want to mount both paths within the emptyDir volume to be able to share files between containers.

  volumeMounts:
    - name: shared-folder
      mountPath: /cache/$(HOSTNAME)

Problem. The second container doesn't resolve /cache/$(HOSTNAME) so instead of mounting /cache/pod-0 it mounts /cache/$(HOSTNAME). I have also tried getting the POD_NAME and setting as env variable but it doesn't resolve it neither.

Dows anybody knows if it is possible to use a path like this (with env variables) in the mountPath attribute?

Upvotes: 3

Views: 3341

Answers (3)

Daniel Marques
Daniel Marques

Reputation: 1405

I tested here and just using Kubernetes (k8s < 1.16) with env variables isn't possible to achieve what you want, basically what is happening is that variable will be accessible only after the pod gets deployed and you're referencing it before it happens.

You can use Helm to define your mounthPath and statefulset with the same value in the values.yaml file, then get this same value and set as a value for the mounthPath field and statefulset name. You can see about this here.

Edit: Follow Matt's answer if you are using k8s 1.17 or higher.

Upvotes: 1

Matt
Matt

Reputation: 8152

To use mountpath with env variable you can use subPath with expanded environment variables (k8s v1.17+).

In your case it would look like following:

containers:
- env:
  - name: MY_POD_NAME
    valueFrom:
      fieldRef:
        fieldPath: metadata.name
  volumeMounts:
  - mountPath: /cache
    name: shared-folder
    subPathExpr: $(MY_POD_NAME)

Upvotes: 3

TheCoolDrop
TheCoolDrop

Reputation: 1066

The problem is that YAML configuration files are POSTed to Kubernetes exactly as they are written. This means that you need to create a templated YAML file, in which you will be able to replace the referenced ti environment variables with values bound to environment variables.

As this is a known "quirk" of Kubernetes there already exist tools to circumvent this problem. Helm is one of those tools which is very pleasant to use

Upvotes: 0

Related Questions