Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

Programming Kubernetes custom resources in Java

January 4, 2023
Rohan Kumar
Related topics:
JavaKubernetes
Related products:
Red Hat OpenShift Container Platform

    Kubernetes 1.16 introduced the concept of custom resources (CRs), allowing users to define their own Kubernetes objects that can be used in their applications. Users are now able to define these Kubernetes object structures tailored to their needs and use them like native Kubernetes resources. This makes Kubernetes much more extensible. These custom resources can be used by Kubernetes Operators to manage applications and their components.

    This article is the second installment in this series:

    • Part 1: How to use Fabric8 Java Client with Kubernetes
    • Part 2:  Programming Kubernetes custom resources in Java
    • Part 3:  How to use Kubernetes dynamic client with Fabric8
    • Part 4: How to generate code using Fabric8 Kubernetes Client
    • Part 5: How to write tests with Fabric8 Kubernetes Client

    In this article, you'll see how you can manipulate the Kubernetes custom resource API programmatically in Java using the Fabric8 Kubernetes client. You'll see some common use cases while using Kubernetes custom resources and try to implement those in Java using the Fabric8 Kubernetes client.

    Getting the client

    The Fabric8 Kubernetes client library should be available on Maven Central. If you're using Maven, you should be able to add it as a dependency in your project by adding the following to the <dependencies> section of your pom.xml file:

    <dependency>
      <groupId>io.fabric8</groupId>
      <artifactId>kubernetes-client</artifactId>
      <version>6.1.1</version>
    </dependency>
    

    Gradle users need to add the following to build.gradle:

    implementation 'io.fabric8:kubernetes-client:6.1.1'
    

    CustomResource POJOs

    We're going to consider the Fabric8 Kubernetes client's typed API here, which means we need to provide a CustomResource type to Fabric8 Kubernetes Client. For this, we need to define some plain Java classes as per our CustomResource's structure. We could use tools like Fabric8 Java Generator or Fabric8 CRD Generator to automatically generate these files instead, but we will cover that process in a separate article.

    All CustomResources defined to Fabric8 Kubernetes Client must extend the io.fabric8.kubernetes.client.CustomResource class. Let's take a look at that class:

    public abstract class CustomResource<S, T> implements HasMetadata {
       // ...
    }
    

    As you can see, it's a generic class that seems to have two arguments:

    • The first argument is for CustomResource's spec field
    • The second argument is for CustomResource's status field

    Why does the Fabric8 Kubernetes client require you to have these fields in the CustomResource? All Kubernetes primitive types (except some types in the core and RBAC apiGroups) seem to have spec and status in their bodies. The main motivation behind this is the separation of concerns:

    • spec is something that the user specifies. It's the user's way of providing the input for the desired state of that object.
    • status is something that should not be modified by the user. It should be the implemented controller/Operator's responsibility to update this field to provide the current state of that object.

    The most common application of CustomResources is Kubernetes Operators. Therefore, it's advisable to use spec and status fields when using CustomResources.

    Let's take a look at the Java classes for a Book custom resource definition. Here's Book.java:

    package io.fabric8.crd.model.v1alpha1;
    
    import io.fabric8.kubernetes.api.model.Namespaced;
    import io.fabric8.kubernetes.client.CustomResource;
    import io.fabric8.kubernetes.model.annotation.Group;
    import io.fabric8.kubernetes.model.annotation.Version;
    
    @Version("v1alpha1")                                             // -> CRD Version
    @Group("testing.fabric8.io")                                     // -> CRD Group
    public class Book                                                    // -> CRD Kind (if not provided in @Kind annotation)
        extends CustomResource<BookSpec, BookStatus>  // -> .spec -> BookSpec , .status -> BookStatus
        implements Namespaced { }                               // -> CRD scope Namespaced

    Here's BookSpec.java:

    package io.fabric8.crd.model.v1alpha1;
    
    public class BookSpec {
        private String title;
        private String author;
        private String isbn;
    
        public String getTitle() {  return title; }
    
        public void setTitle(String title) { this.title = title; }
    
        public String getAuthor() { return author; }
    
        public void setAuthor(String author) { this.author = author; }
    
        public String getIsbn() { return isbn; }
    
        public void setIsbn(String isbn) { this.isbn = isbn; }
    }

    And here's BookStatus.java

    package io.fabric8.crd.model.v1alpha1;
    
    public class BookStatus {
        private boolean issued;
        private String issuedto;
    
        public boolean isIssued() { return issued; }
    
        public void setIssued(boolean issued) { this.issued = issued; }
    
        public String getIssuedto() { return issuedto; }
    
        public void setIssuedto(String issuedto) { this.issuedto = issuedto; }
    }
    

    Creating the custom resource definition

    Just as you would in Java before creating a custom object, to make a custom resource definition you need to create a class first. In order to use a custom resource, you need to first define its structure and register it to the Kubernetes API server in the form of a CustomResourceDefinition.

    We will be taking an example of a simple custom resource called Book. The code snippet below defines the CustomResourceDefinition using the Fabric8 Kubernetes client. It's also possible to automatically generate its YAML file using Fabric8 CRD Generator; we will be covering that in a separate article.

    As you can see, we have defined the structure of our custom resource in the openAPIV3Schema field. You can create a CustomResourceDefinition either using kubectl or using Fabric8 Kubernetes Client, like this:

    try (KubernetesClient client = new KubernetesClientBuilder().build()) {
          CustomResourceDefinition crd = v1CRDFromCustomResourceType(Book.class)
              .editSpec().editVersion(0)
                .withNewSchema()
                  .withNewOpenAPIV3Schema()
                    .withType("object")
                    .addToProperties("spec", new JSONSchemaPropsBuilder()
                        .withType("object")
                        .addToProperties("title", new JSONSchemaPropsBuilder()
                            .withType("string")
                            .build())
                        .addToProperties("author", new JSONSchemaPropsBuilder()
                            .withType("string")
                            .build())
                        .addToProperties("isbn", new JSONSchemaPropsBuilder()
                            .withType("string")
                            .build())
                        .build())
                    .addToProperties("status", new JSONSchemaPropsBuilder()
                        .withType("object")
                        .addToProperties("issued", new JSONSchemaPropsBuilder()
                            .withType("boolean")
                            .build())
                        .addToProperties("issuedto", new JSONSchemaPropsBuilder()
                            .withType("string")
                            .build())
                        .build())
                  .endOpenAPIV3Schema()
                .endSchema()
              .endVersion().endSpec().build();
    
          client.apiextensions().v1()
              .customResourceDefinitions()
              .resource(crd)
              .create();
    }
    

    Once you've created Book CustomResourceDefinition, you can start using Book CustomResource.

    Basic CRUD operations

    If you are already familiar with the Kubernetes client, you'll notice that basic Create, Read, Update, Delete (CRUD) operations for custom resources are not that different from those for regular resources. There is an additional process involved in creating an operation instance for that specific custom resource. Take our Book custom resource as an example. We would need to create a MixedOperation instance like this:

    MixedOperation<Book, KubernetesResourceList<Book>, Resource<Book>> bookOp = client.resources(Book.class);

    Once you've created this object, you can do basic operations:

    try (KubernetesClient client = new KubernetesClientBuilder().build()) {
      // Create Book Client
      MixedOperation<Book, KubernetesResourceList<Book>, Resource<Book>> bookOp = client.resources(Book.class);
    
      // Create Book Object
      Book book1 = createNewBook("head-first-java", "Head First Java", "Kathy Sierra", "9781491910771");
    
      // Create
      bookOp.inNamespace("default").resource(book1).create();
    
      // Read
      book1 = bookOp.inNamespace("default").withName("head-first-java").get();
    
      // List
      KubernetesResourceList<Book> books = bookOp.inNamespace("default").list();
      books.getItems().stream().map(CustomResource::getMetadata).map(ObjectMeta::getName).forEach(logger::info);
    
      // Update
      book1.getSpec().setAuthor("Kathy Sierra, Bert Bates, Trisha Gee");
      bookOp.inNamespace("default").resource(book1).replace();
    
      // Delete
      bookOp.inNamespace("default").resource(book1).delete();
    }
    

    Updating status

    This use case is very common when working on Kubernetes Operators' control loop. Kubernetes Operators are supposed to update the status of a custom resource after processing it during reconciliation. We will be using the same Book custom resource here and try to update its status:

    try (KubernetesClient client = new KubernetesClientBuilder().build()) {
      MixedOperation<Book, KubernetesResourceList<Book>, Resource<Book>> bookOp = client.resources(Book.class);
    
      // Create Book CR
      Book book1 = createNewBook("effective-java", "Effective Java", "Joshua Bloch ", "9788131726594");
      book1 = bookOp.inNamespace("default").resource(book1).create();
    
      // Create Status Object
      BookStatus book1Status = new BookStatus();
      book1Status.setIssued(true);
      book1Status.setIssuedto("Bob");
    
      // Update Status
      book1.setStatus(book1Status);
      bookOp.inNamespace("default").resource(book1).replaceStatus();
    }
    

    Custom resource shared informers

    While using custom resources in applications, it's better to use shared informers rather than plain watch. It's the same as using shared informers for regular resources, with the additional step of creating a client for the custom resource:

    try (KubernetesClient client = new KubernetesClientBuilder().build()) {
      MixedOperation<Book, KubernetesResourceList<Book>, Resource<Book>> bookOp = client.resources(Book.class);
    
      SharedIndexInformer<Book> bookSharedIndexInformer = bookOp.inNamespace("default").inform(new ResourceEventHandler<>() {
        @Override
        public void onAdd(Book book) { logger.info("{} ADDED"); }
    
        @Override
        public void onUpdate(Book book, Book t1) { logger.info("{} UPDATED"); }
    
        @Override
        public void onDelete(Book book, boolean b) { logger.info("{} DELETED"); }
      });
    
      Thread.sleep(30 * 1000L);
      logger.info("Book SharedIndexInformer open for 30 seconds");
    
      bookSharedIndexInformer.close();
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      throw new RuntimeException(e);
    }
    

    Learn more about programming Kubernetes in Java

    This article has shown how to manipulate the Kubernetes custom resource API using the Fabric8 Kubernetes client. You can find all the code for this in this repository. The next article, How to use Kubernetes dynamic client with Fabric8, demonstrates the Fabric8 Kubernetes Dynamic Client. 

    For more information, check out the Fabric8 Kubernetes Client GitHub page. Feel free to follow us on these channels:

    • StackOverflow
    • Fabric8 Kubernetes Client CHEATSHEET
    • Twitter
    • Gitter Chat
    Last updated: January 20, 2023

    Recent Posts

    • Debugging image mode with Red Hat OpenShift 4.20: A practical guide

    • EvalHub: Because "looks good to me" isn't a benchmark

    • SQL Server HA on RHEL: Meet Pacemaker HA Agent v2 (tech preview)

    • Deploy with confidence: Continuous integration and continuous delivery for agentic AI

    • Every layer counts: Defense in depth for AI agents with Red Hat AI

    What’s up next?

    The microservice architectural approach is more than just about technology: It reaches into the foundation of your organization to allow you to build truly scalable, adaptive, complex systems that help a business adapt to rapidly changing competitive markets. In Microservices for Java Developers, you'll get a hands-on introduction to frameworks and containers through a handful of familiar patterns.

    Get the e-book
    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer tools
    • Interactive tutorials
    • API catalog

    Quicklinks

    • Learning resources
    • E-books
    • Cheat sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site status dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2026 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Chat Support

    Please log in with your Red Hat account to access chat support.