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

How to use Kubernetes dynamic client with Fabric8

January 5, 2023
Rohan Kumar
Related topics:
Kubernetes
Related products:
Red Hat Enterprise Linux

    While working with Kubernetes Client, you would mostly be working with standard Kubernetes resources whose model is provided by the library itself. However, it’s not always possible to provide a concrete model type while accessing a Kubernetes API object (e.g., in the case of custom resources). Fabric8 Kubernetes Client’s GenericKubernetesResource API can be used in these scenarios. It allows objects that do not have Java POJOs registered to be manipulated generically.

    This article is the third installment in the following 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

    Getting the Fabric8 Kubernetes client

    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 this to your dependencies section of your pom.xml:

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

    Gradle users need to add this to build.gradle:

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

    The GenericKubernetesResource object

    GenericKubernetesResource is a generic Kubernetes object which can be used to serialize/deserialize any Kubernetes resource. It allows basic access to type metadata and object metadata. All the other stuff needs to be provided in additionalProperties map. While deserializing an unknown resource, common stuff like apiVersion, kind, and metadata would be directly available, but rest would be in additionalProperties map.

    Let’s take a look at an example of creating a GenericKubernetesResource object. We will take example from Kubernetes CustomResourceDefinition docs for CronTab object:

    # Taken from https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#create-custom-objects
    
    apiVersion: "stable.example.com/v1"
    kind: CronTab
    metadata:
      name: my-new-cron-object
    spec:
      cronSpec: "* * * * */5"
      image: my-awesome-cron-image

    We can represent this object in GenericKubernetesResource like this:

    Map<String, Object> spec = new HashMap<>();
    spec.put("cronSpec", "* * * * */5");
    spec.put("image", "my-awesome-cron-image");
    
    
    GenericKubernetesResource genericKubernetesResource = new GenericKubernetesResourceBuilder()
        .withApiVersion("stable.example.com/v1")
        .withKind("CronTab")
        .withNewMetadata()
        .withName("my-new-cron-object")
        .endMetadata()
        .addToAdditionalProperties("spec", spec)
        .build();
    
    System.out.println(Serialization.asYaml(genericKubernetesResource));

    Note that access to type and object metadata is similar to standard Kubernetes resources. However, other fields (like status and spec) are manipulated using plain HashMaps.

    2 entry points for dynamic client

    There are different ways to use GenericKubernetesResource API in Fabric8 Kubernetes Client. Let’s take a look at two approaches:

    • Providing apiVersion and kind: You can start using GenericKubernetesResource API by providing apiVersion and kind to kubernetesClient.genericKubernetesResources() method. Here is an example of creating CronTab object we constructed in the previous section:
      try (KubernetesClient client = new KubernetesClientBuilder().build()) {
        GenericKubernetesResource genericKubernetesResource = createNewCronTab();
                                          // ApiVersion              // Kind
        client.genericKubernetesResources("stable.example.com/v1", "CronTab")
            .inNamespace("default")
            .resource(genericKubernetesResource)
            .create();
      }
      This method would automatically detect resource-related information like group, version, and plural that are required for contacting Kubernetes API server.
    • Providing ResourceDefinitionContext: We can go one step further from the previous approach by providing all the resource-related information to KubernetesClient rather than letting KubenetesClient make assumptions. We can do this by providing information in the form of ResourceDefinitionContext. Check this example:
      try (KubernetesClient client = new KubernetesClientBuilder().build()) {
        GenericKubernetesResource genericKubernetesResource = createNewCronTab();
      
        ResourceDefinitionContext context = new ResourceDefinitionContext.Builder()
            .withGroup("stable.example.com")
            .withVersion("v1")
            .withKind("CronTab")
            .withPlural("crontabs")
            .withNamespaced(true)
            .build();
      
        client.genericKubernetesResources(context)
            .inNamespace("default")
            .resource(genericKubernetesResource)
            .create();
      }

    Basic create, read, update, and delete operations

    Once you’ve provided ResourceDefinitionContext or apiVersion+kind to genericKubernetesResources() DSL method, it’s very easy to perform basic operations since they are the same as standard Kubernetes resources, thanks to KubernetesClient’s fluent DSL.

    The following code snippet gives an overview of the basic operations of CronTab custom resource:

    
    try (KubernetesClient client = new KubernetesClientBuilder().build()) {
      // Create CronTab context
      ResourceDefinitionContext context = new ResourceDefinitionContext.Builder()
          .withGroup("stable.example.com")
          .withVersion("v1")
          .withKind("CronTab")
          .withPlural("crontabs")
          .withNamespaced(true)
          .build();
    
      // Create CronTab Object
      GenericKubernetesResource genericKubernetesResource = createNewCronTab();
    
      // Create
      client.genericKubernetesResources(context)
          .inNamespace("default")
          .resource(genericKubernetesResource)
          .create();
    
      // Read
      genericKubernetesResource = client.genericKubernetesResources(context)
          .inNamespace("default")
          .withName("my-new-cron-object")
          .get();
    
      // List
      GenericKubernetesResourceList cronTabs = client.genericKubernetesResources(context).inNamespace("default").list();
      cronTabs.getItems().stream().map(GenericKubernetesResource::getMetadata).map(ObjectMeta::getName).forEach(logger::info);
    
      // Update
      Map additionalProperties = genericKubernetesResource.getAdditionalProperties();
      Map spec = (Map) additionalProperties.get("spec");
      spec.put("image", "my-updated-cron-image");
      client.genericKubernetesResources(context).inNamespace("default").resource(genericKubernetesResource).replace();
    
      // Delete
      client.genericKubernetesResources(context).inNamespace("default").resource(genericKubernetesResource).delete();
    }
    

    The watch operation

    Like common operations, it’s also possible to watch a resource with the help of GenericKubernetesResource API. Here is an example:

    try (KubernetesClient client = new KubernetesClientBuilder().build()) {
      Watch watch = client.genericKubernetesResources("stable.example.com/v1", "CronTab")
          .inNamespace("default")
          .watch(new Watcher<>() {
            @Override
            public void eventReceived(Action action, GenericKubernetesResource genericKubernetesResource) {
              logger.info("{} {}", action.name(), genericKubernetesResource.getMetadata().getName());
            }
    
            @Override
            public void onClose(WatcherException e) {
              logger.info("Closing due to {} ", e.getMessage());
            }
          });
    
      logger.info("Watch open for 30 seconds");
      Thread.sleep(30 * 1000L);
      watch.close();
    
      logger.info("Watch closed");
    }

    The Fabric8 Kubernetes Client GitHub and more

    This article demonstrated how to manipulate Kubernetes CustomResource API using Fabric8 Kubernetes Client. You can find the code in this repository. Check out the final two articles in this series discussing testing and the code generation capabilities of Fabric8.

    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: September 20, 2023

    Related Posts

    • Write a simple Kubernetes Operator in Java using the Fabric8 Kubernetes Client

    • Migrating from Fabric8 Maven Plugin to Eclipse JKube 1.0.0

    • Getting started with the fabric8 Kubernetes Java client

    Recent Posts

    • Trusted software factory: Building trust in the agentic AI era

    • Build a zero trust AI pipeline with OpenShift and RHEL CVMs

    • Red Hat Hardened Images: Top 5 benefits for software developers

    • How EvalHub manages two-layer Kubernetes control planes

    • Tekton joins the CNCF as an incubating project

    What’s up next?

    Learn and experiment with Kubernetes using the free Developer Sandbox for Red Hat OpenShift! This step-by-step tutorial walks developers through how to use Kubernetes to create an application. We strive to make developers' work easier by making Kubernetes development simple, fast, and fun.

    Start the activity
    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.