Copy locust file into volume via YML in kubernetes

10/13/2020

I have a yml file that I took from a github repository.

apiVersion: v1
kind: ConfigMap
metadata:
  name: scripts-cm
data:
  locustfile.py: |
    from locust import HttpLocust, TaskSet, task


    class UserTasks(TaskSet):

        @task
        def index(self):
            self.client.get("/")

        @task
        def stats(self):
            self.client.get("/stats/requests")


    class WebsiteUser(HttpLocust):
        task_set = UserTasks

But I don't want to set my configure management to do this as I have a separate locustfile.py and it is quite big. Is there a way to copy the file in the data attribute instead? or I have to use cat command?

-- Moses Liao GZ
kubernetes
locust

1 Answer

10/19/2020

Is there a way to copy the file in the data attribute instead?

Yes there is. You can create a configMap from a file and mount this configMap as a Volume to a Pod. I've prepared an example to show you the whole process.

Let's assume that you have your locustfile.py with only the Python script:

from locust import HttpLocust, TaskSet, task


class UserTasks(TaskSet):

    @task
    def index(self):
        self.client.get("/")

    @task
    def stats(self):
        self.client.get("/stats/requests")


class WebsiteUser(HttpLocust):
    task_set = UserTasks

You will need to create a configMap from this file with following command:

  • $ kubectl create configmap scripts-cm --from-file=locustfile.py

After that you can mount this configMap as a Volume like in the example below:

apiVersion: v1
kind: Pod
metadata:
  name: ubuntu
spec:
  containers:
    - name: ubuntu
      image: ubuntu
      command: 
      - sleep 
      - "infinity" 
      volumeMounts:
      - name: config-volume
        mountPath: /app/ # <-- where you would like to mount your files from a configMap 
  volumes:
    - name: config-volume
      configMap:
        name: scripts-cm # <-- name of your configMap
  restartPolicy: Never

You can then check if your files are placed correctly in the /app directory:

  • $ kubectl exec -it ubuntu -- ls /app/
locustfile.py

A tip!

You can add multiple files to a configMap by

  • --from-file=one.py --from-file=two.py ...

You can also run --from-file=. (use all the files from directory).


Additional resources:

-- Dawid Kruk
Source: StackOverflow