How to create Statefulsets workloads Using Kubernetes Python Client

black and gray laptop computer turned on doing computer codes
Reading Time: 3 minutes

Hello Readers! In this blog we are going to see how we can create a Statefulsets using kubernetes python client . Kubectl is the primary tool for dealing with and managing your clusters from the command line.

Through kubectl you can see the status of individual nodes, pods on those nodes, policies and much more besides. But In this blog we will see how we can use python for doing these things with resources. 

Prerequisites:

Installing Kubernetes in your system.

Before we move forward with creating Statefulsets using K8s python client we have some prerequisites that we need to follow.

Kubernetes library provides us modules such as client and config which we will use here. So, let’s install Kubernetes Python Client using below commands:

pip3 install kubernetes
statefulset

In my case I have already installed in it, that’s why its show us already satisfied.

Now, we have the python-kubernetes package-installed.

So, let’s get started!

Step1. Creating the Statefulsets:

I will create a one directory and inside this I will make a file named statefulset.py. 

mkdir kubernetes

cd kubernetes

touch statefulset.py

My statefulset.py file contains the following code for creating a statefulsets using Kubernetes Python Client. Now that we have the python-kubernetes package installed, we can import it as:

from kubernetes import client, config

Inside this code I am creating functions first one is create_service( ) and second one is create_stateful_set_object( ) and third one is create_stateful_set( ) . I am creating this statefulsets in my default namespace, if you want you can use another also. 

from kubernetes import client, config


def create_service(core_v1_api):
    body = client.V1Service(
        api_version="v1",
        kind="Service",
        metadata=client.V1ObjectMeta(
            name="redis-test-svc"
        ),
        spec=client.V1ServiceSpec(
            selector={"app": "redis"},
            cluster_ip="None",
            type="ClusterIP",
            ports=[client.V1ServicePort(
                port=6379,
                target_port=6379
            )]
        )
    )
    # Create the service in specified namespace
    # (Can replace "default" with a namespace you may have created)
    core_v1_api.create_namespaced_service(namespace="default", body=body)


def create_stateful_set_object():
    container = client.V1Container(
        name="sts-redis",
        image="redis",
        image_pull_policy="IfNotPresent",
        ports=[client.V1ContainerPort(container_port=6379)],
    )
    # Template
    template = client.V1PodTemplateSpec(
        metadata=client.V1ObjectMeta(labels={"app": "redis"}),
        spec=client.V1PodSpec(containers=[container]))
    # Spec
    spec = client.V1StatefulSetSpec(
        replicas=1,
        service_name="redis-test-svc",
        selector=client.V1LabelSelector(
            match_labels={"app": "redis"}
        ),
        template=template)
    # StatefulSet
    statefulset = client.V1StatefulSet(
        api_version="apps/v1",
        kind="StatefulSet",
        metadata=client.V1ObjectMeta(name="statefulset-redis"),
        spec=spec)

    return statefulset


def create_stateful_set(apps_v1_api, stateful_set_object):
    # Create the Statefulset in default namespace
    # You can replace the namespace with you have created
    apps_v1_api.create_namespaced_stateful_set(
        namespace="default", body=stateful_set_object
    )

def main():
    # Loading the local kubeconfig
    config.load_kube_config()
    apps_v1_api = client.AppsV1Api()
    core_v1_api = client.CoreV1Api()
    stateful_set_obj = create_stateful_set_object()

    create_service(core_v1_api)

    create_stateful_set(apps_v1_api, stateful_set_obj)

if __name__ == "__main__":
    main()

Now, It’s time to create the statefulsets. So, I will now run the python code.

$ python3 statefulset.py

As you can see here my statefulset is successfully created.

Step2. Updating the Statefulsets:

For updating this statefulsets I will create a file named update.py. Inside this file I will update the container image here. My file contains the following code for updating the statefulsets:

from kubernetes import client, config


def create_stateful_set_object():
    container = client.V1Container(
        name="sts-redis",
        image="redis",
        image_pull_policy="IfNotPresent",
        ports=[client.V1ContainerPort(container_port=6379)],
    )
    # Template
    template = client.V1PodTemplateSpec(
        metadata=client.V1ObjectMeta(labels={"app": "redis"}),
        spec=client.V1PodSpec(containers=[container]))
    # Spec
    spec = client.V1StatefulSetSpec(
        replicas=1,
        service_name="redis-test-svc",
        selector=client.V1LabelSelector(
            match_labels={"app": "redis"}
        ),
        template=template)
    # StatefulSet
    statefulset = client.V1StatefulSet(
        api_version="apps/v1",
        kind="StatefulSet",
        metadata=client.V1ObjectMeta(name="statefulset-redis"),
        spec=spec)

    return statefulset


def create_stateful_set(apps_v1_api, stateful_set_object):
    # Create the Statefulset in default namespace
    # You can replace the namespace with you have created
    apps_v1_api.create_namespaced_stateful_set(
        namespace="default", body=stateful_set_object
    )



def update_stateful_set(apps_v1_api, statefulset):
    # Update container image
    statefulset.spec.template.spec.containers[0].image = "redis:6.2"
    statefulset_name = statefulset.metadata.name
    # Patch the statefulset
    apps_v1_api.patch_namespaced_stateful_set(
        name=statefulset_name, namespace="default", body=statefulset
    )



def main():
    # Loading the local kubeconfig
    config.load_kube_config()
    apps_v1_api = client.AppsV1Api()
    core_v1_api = client.CoreV1Api()
    stateful_set_obj = create_stateful_set_object()
    create_stateful_set(apps_v1_api, stateful_set_obj)

    update_stateful_set(apps_v1_api, stateful_set_obj)


if __name__ == "__main__":
    main()

Here in this code I have used update_stateful_set( ) function for updating this staefulsets. Inside this function, I am updating the container image. Now, I will run the code for updation:

$ python3 update.py

As you can see here that my container image got updated:

sts

So, We are successfully done now. This is how we can play with the Kubernetes python client

Conclusion:

Thank you for sticking to the end. In this blog we have seen how easily we can create and update a statefulsets using kubernetes python client. If you like this blog, please do show your appreciation by giving thumbs ups and share this blog and give me suggestions on how I can improve my future posts to suit your needs.Here is my Email: gayatri.singh@knoldus.com

Written by 

I am an enthusiastic , hard-working and determine girl with strong attention to detail and eager to learn about new technologies.

Leave a Reply