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?
- Commit the code to the GCP Source Code Repositories
- A CloudBuild trigger (docs: https://cloud.google.com/cloud-build/docs/) that creates the container
- Create a trigger (can be a CronJob) that runs the code that deploys the Job.
- 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
- Contains a pod template spec object
- Contains a pod template 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:
5 Comments. Leave new
Dear Carlos,
when we call create_namespaced_job, can we have a way to wait for the job done?
Thanks
delete job error.
you should add body=deleteoptions
Mr. Rolo,
Great post. It really helped me get started on my project. Just one note you may want to update the program to reflect the new API version. I had to take out ‘include_uninitialized=False,’ in a few places to get the program to run.
Thanks again for such a useful post.
-S
Thank you for the code example.
Actually, after some research and trial, I found that you could enable kube_cleanup_finished_jobs() to clean up all dependency pods without calling kube_delete_empty_pods() directly.
by change kube_cleanup_finished_jobs() setting
“`
body = client.V1DeleteOptions(propagation_policy=’Background’)
“`
also please take out ‘include_uninitialized=False,’
* reference
https://github.com/kubernetes-client/python/issues/234
fails for me
api_instance.get_api_resources()
throws
{MaxRetryError}HTTPConnectionPool(host=’localhost’, port=80): Max retries exceeded with url: /apis/batch/v1/ (Caused by NewConnectionError(‘: Failed to establish a new connection: [Errno 61] Connection refused’))