How to allow a Kubernetes Job access to a file on host

10/22/2018

I've been though the Kubernetes documentation thoroughly but am still having problems interacting with a file on the host filesystem with an application running inside a K8 job launched pod. This happens with even the simplest utility so I have included an stripped down example of my yaml config. The local file, 'hello.txt', referenced here does exist in /tmp on the host (ie. outside the Kubernetes environment) and I have even chmod 777'd it. I've also tried different places in the hosts filesystem than /tmp.

The pod that is launched by the Kubernetes Job terminates with Status=Error and generates the log ls: /testing/hello.txt: No such file or directory

Because I ultimately want to use this programmatically as part of a much more sophisticated workflow it really needs to be a Job not a Deployment. I hope that is possible. My current config file which I am launching with kubectl just for testing is:

apiVersion: batch/v1
kind: Job
metadata:
  name: kio
  namespace: kmlflow
spec:
  # ttlSecondsAfterFinished: 5
  template:
    spec:
      containers:
      - name: kio-ingester
        image: busybox
        volumeMounts:
        - name: test-volume
          mountPath: /testing
        imagePullPolicy: IfNotPresent
        command: ["ls"]
        args: ["-l", "/testing/hello.txt"]
      volumes:
      - name: test-volume
        hostPath:
          # directory location on host
          path: /tmp
          # this field is optional
          # type: Directory
      restartPolicy: Never
  backoffLimit: 4

Thanks in advance for any assistance.

-- jpjenk
kubernetes

1 Answer

10/22/2018

Looks like when the volume is mounted , the existing data can't be accessed.

You will need to make use of init container to pre-populate the data in the volume.

apiVersion: v1
kind: Pod
metadata:
  name: my-app
spec:
  containers:
  - name: my-app
    image: my-app:latest
    volumeMounts:
    - name: config-data
      mountPath: /data
  initContainers:
  - name: config-data
    image: busybox
    command: ["echo","-n","{'address':'10.0.1.192:2379/db'}", ">","/data/config"]
    volumeMounts:
    - name: config-data
      mountPath: /data
  volumes:
  - name: config-data
    hostPath: {}

Reference:

https://medium.com/@jmarhee/using-initcontainers-to-pre-populate-volume-data-in-kubernetes-99f628cd4519

-- Ijaz Ahmad Khan
Source: StackOverflow