Pythian Blog: Technical Track

How to creates Kubernetes jobs with Python

In this blog post I will do a quick guide, with some code examples, on how to deploy a Kubernetes Job programmatically, using Python as the language of choice. For this I’m using GKE (Google Kubernetes Engine), logging via StackTrace and haveana image available on Google Container Registry. The architecture should be something like this: The code that I created:
  • A Dockerfile for my container
  • A Python App that has the code to run (this will be the Job)
How does all this works?
  1. Commit the code to the GCP Source Code Repositories
  2. A CloudBuild trigger (docs: https://cloud.google.com/cloud-build/docs/) that creates the container
  3. Create a trigger (can be a CronJob) that runs the code that deploys the Job.
    1. For this exercise, I’m going to trigger the Job creation from my own laptop.
Now the code. The difficult part here was dealing a bit with the documentation. For this code I used the following library: https://github.com/kubernetes-client/python/tree/master/kubernetes It provides the Kubernetes abstraction layer and greatly simplifies the work. Now, to deploy a Kubernetes Job, our code needs to build the following objects:
  • Job object
    • Contains a metadata object
    • Contains a job spec object
      • Contains a pod template object
        • Contains a pod template spec object
          • Contains a container object
You can walk through the Kubernetes library code and check how it gets and forms the objects. Also, don’t forget that all this is based on the official Job specification ( https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/#writing-a-job-spec) Without much else to say, you can check the full code here:

No Comments Yet

Let us know what you think

Subscribe by email