How To Create Deployment via Kubernetes Python Client :

Reading Time: 3 minutes

Hello Folks.. I hope you all are doing so well. In this blog we will see how we can create a deployment using Kubernetes python client. Like we all know that generally we use kubectl commands for creating, listing, updating, deleting the kubernetes resources. But In this blog we will see how we can use python for doing these things with resources. Its going to be interested so stay tuned.

Prerequisites :

Before we start creating deployment using kubernetes python client. We need to follow some prerequisites like:

So, we need to install Kubernetes Python Client:

$ pip install kubernetes

The kubernetes python client is successfully installed now.

So; now let’s see how we can create a deployment via kubernetes python client.

Creating Deployment :

Now I create one directory on my desktop name is deployment :

or in this directory i have created two files i.e. nginx-deployment.yaml :

why i created nginx-deployment.yaml file because i created deployment via passing yaml file.

now; i created deployment for that i have to import the python client in my file

from kubernetes import client, config

Below is the code for creating deployment via python client :

from os import path

import yaml

from kubernetes import client, config

def main():
    # Configs can be set in Configuration class directly or using helper
    # utility. If no argument provided, the config will be loaded from
    # default location.

    with open(path.join(path.dirname(__file__), "nginx-deployment.yaml")) as f:
        dep = yaml.safe_load(f)
        k8s_apps_v1 = client.AppsV1Api()
        resp = k8s_apps_v1.create_namespaced_deployment(
            body=dep, namespace="default")
        print("Deployment created. status='%s'" %

if __name__ == '__main__':

Here; is my nginx-deployment.yaml file that i pass in my file :

apiVersion: apps/v1
kind: Deployment
  name: nginx-deployment
    app: nginx
  replicas: 3
      app: nginx
        app: nginx
      - name: nginx
        image: nginx:1.15.4
        - containerPort: 80

Now let’s run the file using command is :


Now; if i check my deployment is created is not i will simply run the command :

kubectl get deployment

so; you can see my deployment nginx-deployment is successfully created.

Conclusion :

So; in this blog we have seen how easily we created deployment using kubernetes python client. I hope this blog will help you.

Happy Learning..

References :

Written by 

Mayuri Dhote is a Software Consultant at Knoldus Software. She has completed her MCA from VIT University. She has very dedicated towards her work. She has always ready to learn new things. Her practice area is Devops. When not working, you will find her writing poems and poetry.