Python script for automating Kubernetes deployment


In this blog, we will write a Python script to automate the deployment of Kubernetes resources using the Kubernetes module. It is a Python client library. Using it we can interact with Kubernetes REST API to manage resources on our Kubernetes cluster.

To install the Kubernetes module use the following command.

pip3 install Kubernetes

Using the following python script we will create a Kubernetes object in a non-default namespace “dev”. We have defined the Deployment object using a Python dictionary. You can specify deployments to make new ReplicaSets or to delete current deployments and replace them with new deployments that use all of their resources.

Our python script will take a unique ID as an argument so that we can create deployments with unique resource names.


Next, we need to connect to Kubernetes API. We will use config.load_kube_function()  to access the kubeconfig file. By default, it loads the kubeconfig file from $HOME/.kube/config. We will manage the deployment object using client.AppsV1Api which allows us to work with all the resources that belong to apiVersion: apps/v1

Now we will write a function to create a deployment object. It will also verify that the object is successfully deployed.



from kubernetes import client, config
import sys
import time
from logzero import logger
from chaoslib.exceptions import ActivityFailed
  ns = "dev"
  unique_id = sys.argv[1]
  manifest = {
      "apiVersion": "apps/v1",
      "kind": "Deployment",
      "metadata": {"name": deployment_name},
      "spec": {"replicas": 1,
               "selector": {
                  "matchLabels": {
                      "app": "dev"
          "template": {"metadata": {"labels": {"app": "dev"}},
              "spec": {"containers": [
                  {"name": "webapp", "image": "nginx"}]

  v1 = client.AppsV1Api()
  field_selector = "{name}".format(name=deployment_name)
  def create_deploy():
   list = v1.list_namespaced_deployment(namespace = ns)
   for i in list.items:

   if  deployment_name in deploy_names:
      raise Exception("Invalid Argument: Resource already exists")
     deploy = v1.create_namespaced_deployment(body = manifest, namespace = ns)
     print("Waiting for Deployment to become ready...")

  def deploy_status():
      ret = v1.list_namespaced_deployment(ns, field_selector=field_selector)
      for d in ret.items:
                  logger.debug("Deployment has '{s}' available replicas".format(s=d.status.available_replicas))

                  if d.status.available_replicas != d.spec.replicas:
                     raise ActivityFailed( "Deployment '{name}' failed".format(name=deployment_name))
                     print("Deployment '{name}' successful".format(name=deployment_name))

except Exception as e:

Now we will execute our script to create this deployment object.

python unique_id_001



This blog is written by our DevOps engineer. You can Please contact with our Virtual CTO Consultants to discuss cloud DevOps infrastructure and product development best practices.

Leave a Reply

Your email address will not be published.