All About Kubernetes Custom Resources | Custom Resources Definition (CRD) | Custom Controller

In Kubernetes, Custom Resource is an extension of the Kubernetes API that allows you to define your custom resources and their schemas.

Why do we need Kubernetes Custom Resources (CRs)?

Kubernetes provides a set of core resources like Pods, Deployments, and Services to manage containerized applications. However, these resources may not cover all use cases or meet specific requirements of complex applications. Custom Resources allow users to define their own resource types tailored to their application's needs.

What is a Custom Resource Definition (CRD)?

  • A Custom Resource Definition is a configuration that defines a Custom Resource's structure and validation rules.

  • It specifies the API version, kind, and the schema for the CR.

  • CRDs are created to enable the use of specific CRs and provide a schema for them.

What is a Custom Controller?

  • A Custom Controller is a piece of software that watches for changes in Custom Resources.

  • It can take actions in response to CR changes, such as creating, updating, or deleting other Kubernetes resources.

  • Custom Controllers allow you to automate tasks based on application-specific requirements.

Real-life Example (E-commerce Application):

In an e-commerce application, Custom Resources could be used to define resources such as product catalogs, orders, and customer accounts. For instance, a Custom Resource named Product could define attributes like name, description, price, and inventory levels for each product in the catalog. Another Custom Resource named Order could represent an order placed by a customer, including details such as items, quantities, shipping address, and order status. By defining these Custom Resources, developers can manage and automate various aspects of the e-commerce application directly within Kubernetes, leveraging its robust ecosystem and tooling

Custom Resource

A Custom Resource in Kubernetes is an extension of the Kubernetes API that allows you to define your custom resources and their schemas. These resources are not part of the core Kubernetes objects but are intended to meet specific application or workload requirements. Custom Resources enable you to work with application-specific configurations and objects within the Kubernetes ecosystem.

  1. What is a Custom Resource in Kubernetes?

    • A Custom Resource is a resource type that extends Kubernetes' core objects.

    • It is defined by you to represent application-specific configurations or objects.

    • CRs can be created, updated, and deleted like standard Kubernetes resources.

    • They enable you to customize and manage complex, application-specific settings.

  2. Why do you need a Custom Resource in Kubernetes?

    • Custom Resources are useful when your application has specific requirements that are not met by the core Kubernetes objects.

    • They allow you to manage application-specific configurations and objects using Kubernetes-native tools.

    • CRs help you achieve a higher level of abstraction, simplifying management.

  3. What is a Custom Resource Definition (CRD)?

    • A Custom Resource Definition is a configuration that defines a Custom Resource's structure and validation rules.

    • It specifies the API version, kind, and the schema for the CR.

    • CRDs are created to enable the use of specific CRs and provide a schema for them.

  4. What is a Custom Controller?

    • A Custom Controller is a piece of software that watches for changes in Custom Resources.

    • It can take actions in response to CR changes, such as creating, updating, or deleting other Kubernetes resources.

    • Custom Controllers allow you to automate tasks based on application-specific requirements.

Example: E-commerce Website with Custom Resources

Suppose you're running an e-commerce website on Kubernetes and want to use Custom Resources to manage product categories. Here's how you can implement this using Custom Resources and a Custom Controller:

Step 1: Create a Custom Resource Definition (CRD)

Define a CRD named ProductCategory that specifies the structure of product categories. The CRD might look like this:

Create a file named product_category_crd.yaml:

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: productcategories.example.com
spec:
  group: example.com
  names:
    kind: ProductCategory
    listKind: ProductCategoryList
    plural: productcategories
    singular: productcategory
  scope: Namespaced
  versions:
    - name: v1
      served: true
      storage: true
  subresources:
    status: {}
  validation:
    openAPIV3Schema:
      type: object
      properties:
        spec:
          type: object
          properties:
            name:
              type: string
            description:
              type: string

Apply the CRD:

kubectl apply -f product_category_crd.yaml

Step 2: Create Custom Resources

You can create instances of ProductCategory as Custom Resources to represent different product categories. For instance:

Create a file named product_category_cr.yaml:

apiVersion: example.com/v1
kind: ProductCategory
metadata:
  name: electronics
spec:
  name: Electronics
  description: Electronic gadgets and devices
  attributes:
    - type: string
      name: color
    - type: number
      name: size
    - type: string
      name: brand
---
apiVersion: example.com/v1
kind: ProductCategory
metadata:
  name: clothing
spec:
  name: Clothing
  description: Fashion apparel and accessories
   attributes:
    - type: string
      name: color
    - type: number
      name: size
    - type: string
      name: brand

Apply the Custom Resource:

kubectl apply -f product_category_cr.yaml

Step 3: Develop a Custom Controller

Write a Custom Controller in a language like Go, Python, or any supported by Kubernetes client libraries. Your controller should watch for changes in ProductCategory Custom Resources and act accordingly.

Create a Python script, e.g., product_category_controller.py:

Here's a simplified example in Python:

from kubernetes import client, config, watch

def manage_product_categories():
    config.load_kube_config()
    v1 = client.CoreV1Api()
    resource_version = ''
    while True:
        stream = watch.Watch().stream(v1.list_namespace)
        for event in stream:
            if event['type'] == 'ADDED':
                handle_added_event(event)
            elif event['type'] == 'MODIFIED':
                handle_modified_event(event)
            elif event['type'] == 'DELETED':
                handle_deleted_event(event)

def handle_added_event(event):
    # Logic for handling the added event
    pass

def handle_modified_event(event):
    # Logic for handling the modified event
    pass

def handle_deleted_event(event):
    # Logic for handling the deleted event
    pass

if __name__ == '__main__':
    manage_product_categories()

Run the Custom Controller

Run the Python script to start the controller:

python product_category_controller.py

This is a simplified example that demonstrates the structure of a Custom Resource Definition, creation of Custom Resources, and the structure of a Custom Controller. In practice, your Custom Controller should implement the desired logic based on the changes in Custom Resources.

With Custom Resources and a Custom Controller, you can manage product categories and take automated actions when they are created, updated, or deleted in your e-commerce website running on Kubernetes.