Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

How to use Kubernetes dynamic client with Fabric8

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

Share:

    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

    • Integrate Red Hat AI Inference Server & LangChain in agentic workflows

    • Streamline multi-cloud operations with Ansible and ServiceNow

    • Automate dynamic application security testing with RapiDAST

    • Assessing AI for OpenShift operations: Advanced configurations

    • OpenShift Lightspeed: Assessing AI for OpenShift operations

    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

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    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

    Red Hat legal and privacy links

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

    Report a website issue