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(); }
- 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:
Last updated: September 20, 2023