CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-io-fabric8--kubernetes-client

Java client for Kubernetes and OpenShift providing access to the full Kubernetes & OpenShift REST APIs via a fluent DSL

Pending
Overview
Eval results
Files

core-resources.mddocs/

Core Resources

The Fabric8 Kubernetes Client provides fluent DSL operations for all standard Kubernetes resources. This includes fundamental resources like Pods, Services, ConfigMaps, Secrets, Namespaces, and more. All operations follow consistent patterns with type-safe interfaces.

Core Operation Interfaces

MixedOperation Interface

The primary interface for resource operations that can work both within specific namespaces and across all namespaces.

public interface MixedOperation<T extends HasMetadata, L extends KubernetesResourceList<T>, R extends Resource<T>> 
    extends NonNamespaceOperation<T, L, R> {
    
    // Namespace-scoped operations
    NonNamespaceOperation<T, L, R> inNamespace(String namespace);
    NonNamespaceOperation<T, L, R> inAnyNamespace();
    
    // All methods from NonNamespaceOperation are also available
}

NonNamespaceOperation Interface

Base interface providing core CRUD and query operations for resources.

public interface NonNamespaceOperation<T extends HasMetadata, L extends KubernetesResourceList<T>, R extends Resource<T>> {
    // Resource selection
    R withName(String name);
    NonNamespaceOperation<T, L, R> withLabel(String key, String value);
    NonNamespaceOperation<T, L, R> withLabelSelector(LabelSelector selector);
    NonNamespaceOperation<T, L, R> withField(String key, String value);
    NonNamespaceOperation<T, L, R> withFieldSelector(String fieldSelector);
    
    // List operations
    L list();
    L list(ListOptions listOptions);
    
    // Bulk operations
    Boolean delete();
    Boolean delete(DeleteOptions deleteOptions);
    
    // Watch operations
    Watch watch(Watcher<T> watcher);
    Watch watch(String resourceVersion, Watcher<T> watcher);
    Watch watch(ListOptions listOptions, Watcher<T> watcher);
    
    // Waiting operations
    List<T> waitUntilReady(long amount, TimeUnit timeUnit) throws InterruptedException;
    List<T> waitUntilCondition(Predicate<T> condition, long amount, TimeUnit timeUnit) throws InterruptedException;
}

Resource Interface

Interface for operations on individual Kubernetes resources.

public interface Resource<T extends HasMetadata> {
    // Basic CRUD operations
    T get();
    T create();
    T delete();
    Boolean delete(DeleteOptions deleteOptions);
    T update();
    T patch(String patch);
    T patch(PatchContext patchContext, String patch);
    T replace();
    
    // Advanced operations
    T fromServer();
    T require();
    T item();
    boolean isReady();
    T waitUntilReady(long amount, TimeUnit timeUnit);
    T waitUntilCondition(Predicate<T> condition, long amount, TimeUnit timeUnit);
    
    // Resource version locking
    ReplaceDeletable<T> lockResourceVersion();
    ReplaceDeletable<T> lockResourceVersion(String resourceVersion);
    
    // Watch operations
    Watch watch(Watcher<T> watcher);
    
    // Edit operations
    T edit();
    T edit(Visitor<T> visitor);
    T editStatus();
    T editStatus(Visitor<T> visitor);
    
    // Configuration for delete operations
    Resource<T> cascading(boolean cascading);
    Resource<T> withGracePeriod(long gracePeriodSeconds);
    Resource<T> withPropagationPolicy(DeletionPropagation propagationPolicy);
    
    // Dry run operations
    Resource<T> dryRun(boolean isDryRun);
}

Core Resource Types

Pods

Pod operations with specialized functionality for container management.

public interface KubernetesClient {
    MixedOperation<Pod, PodList, PodResource> pods();
}

// Pod-specific operations are in PodResource (see Pod Operations doc)

Usage Examples:

// List all pods in current namespace
PodList pods = client.pods().list();

// Get a specific pod
Pod pod = client.pods().withName("my-pod").get();

// Create a pod
Pod newPod = client.pods().create(new PodBuilder()
    .withNewMetadata()
        .withName("example-pod")
        .withLabels(Map.of("app", "example"))
    .endMetadata()
    .withNewSpec()
        .addNewContainer()
            .withName("app")
            .withImage("nginx:1.21")
            .addNewPort()
                .withContainerPort(80)
            .endPort()
        .endContainer()
    .endSpec()
    .build());

// Delete pods by label
client.pods().withLabel("app", "example").delete();

// Watch for pod changes
Watch watch = client.pods().watch(new Watcher<Pod>() {
    @Override
    public void eventReceived(Action action, Pod pod) {
        System.out.println(action + ": " + pod.getMetadata().getName());
    }
    
    @Override
    public void onClose(WatcherException cause) {
        System.out.println("Watch closed: " + cause);
    }
});

Services

Service operations for network access management.

public interface KubernetesClient {
    MixedOperation<Service, ServiceList, ServiceResource> services();
}

Usage Examples:

// Create a service
Service service = client.services().create(new ServiceBuilder()
    .withNewMetadata()
        .withName("my-service")
        .withLabels(Map.of("app", "example"))
    .endMetadata()
    .withNewSpec()
        .withSelector(Map.of("app", "example"))
        .addNewPort()
            .withPort(80)
            .withTargetPort(new IntOrString(8080))
            .withProtocol("TCP")
        .endPort()
        .withType("ClusterIP")
    .endSpec()
    .build());

// Update service
Service updatedService = client.services().withName("my-service").edit(s -> 
    new ServiceBuilder(s)
        .editSpec()
            .withType("LoadBalancer")
        .endSpec()
        .build());

// List services with label selector
ServiceList services = client.services()
    .withLabelSelector(new LabelSelectorBuilder()
        .addToMatchLabels("app", "example")
        .build())
    .list();

ConfigMaps

ConfigMap operations for configuration data management.

public interface KubernetesClient {
    MixedOperation<ConfigMap, ConfigMapList, Resource<ConfigMap>> configMaps();
}

Usage Examples:

// Create a ConfigMap
ConfigMap configMap = client.configMaps().create(new ConfigMapBuilder()
    .withNewMetadata()
        .withName("app-config")
    .endMetadata()
    .withData(Map.of(
        "database.url", "jdbc:postgresql://localhost:5432/mydb",
        "cache.enabled", "true",
        "log.level", "INFO"
    ))
    .build());

// Update ConfigMap data
client.configMaps().withName("app-config").edit(cm ->
    new ConfigMapBuilder(cm)
        .addToData("new.property", "new-value")
        .build());

// Get ConfigMap data
ConfigMap cm = client.configMaps().withName("app-config").get();
String dbUrl = cm.getData().get("database.url");

Secrets

Secret operations for sensitive data management.

public interface KubernetesClient {
    MixedOperation<Secret, SecretList, Resource<Secret>> secrets();
}

Usage Examples:

// Create a generic secret
Secret secret = client.secrets().create(new SecretBuilder()
    .withNewMetadata()
        .withName("app-secrets")
    .endMetadata()
    .withType("Opaque")
    .withData(Map.of(
        "username", Base64.getEncoder().encodeToString("admin".getBytes()),
        "password", Base64.getEncoder().encodeToString("secret123".getBytes())
    ))
    .build());

// Create a TLS secret
Secret tlsSecret = client.secrets().create(new SecretBuilder()
    .withNewMetadata()
        .withName("tls-secret")
    .endMetadata()
    .withType("kubernetes.io/tls")
    .withData(Map.of(
        "tls.crt", Base64.getEncoder().encodeToString(certData),
        "tls.key", Base64.getEncoder().encodeToString(keyData)
    ))
    .build());

// Read secret data
Secret secret = client.secrets().withName("app-secrets").get();
String username = new String(Base64.getDecoder().decode(secret.getData().get("username")));

Namespaces

Namespace operations for resource isolation and organization.

public interface KubernetesClient {
    NonNamespaceOperation<Namespace, NamespaceList, Resource<Namespace>> namespaces();
}

Usage Examples:

// Create a namespace
Namespace namespace = client.namespaces().create(new NamespaceBuilder()
    .withNewMetadata()
        .withName("development")
        .withLabels(Map.of("environment", "dev"))
    .endMetadata()
    .build());

// List all namespaces
NamespaceList namespaces = client.namespaces().list();

// Check if namespace exists
boolean exists = client.namespaces().withName("production").get() != null;

// Delete namespace (this will delete all resources in the namespace)
client.namespaces().withName("old-namespace").delete();

Nodes

Node operations for cluster node management.

public interface KubernetesClient {
    NonNamespaceOperation<Node, NodeList, Resource<Node>> nodes();
}

Usage Examples:

// List all nodes
NodeList nodes = client.nodes().list();

// Get node details
Node node = client.nodes().withName("worker-node-1").get();
NodeStatus status = node.getStatus();
List<NodeCondition> conditions = status.getConditions();

// Label a node
client.nodes().withName("worker-node-1").edit(n ->
    new NodeBuilder(n)
        .editMetadata()
            .addToLabels("node-role", "worker")
        .endMetadata()
        .build());

// Cordon a node (mark as unschedulable)
client.nodes().withName("worker-node-1").edit(n ->
    new NodeBuilder(n)
        .editSpec()
            .withUnschedulable(true)
        .endSpec()
        .build());

Persistent Volumes and Claims

Storage operations for persistent data management.

public interface KubernetesClient {
    NonNamespaceOperation<PersistentVolume, PersistentVolumeList, Resource<PersistentVolume>> persistentVolumes();
    MixedOperation<PersistentVolumeClaim, PersistentVolumeClaimList, Resource<PersistentVolumeClaim>> persistentVolumeClaims();
}

Usage Examples:

// Create a PersistentVolumeClaim
PersistentVolumeClaim pvc = client.persistentVolumeClaims().create(new PersistentVolumeClaimBuilder()
    .withNewMetadata()
        .withName("app-storage")
    .endMetadata()
    .withNewSpec()
        .withAccessModes("ReadWriteOnce")
        .withNewResources()
            .addToRequests("storage", new Quantity("10Gi"))
        .endResources()
        .withStorageClassName("fast-ssd")
    .endSpec()
    .build());

// List PVCs by storage class
PersistentVolumeClaimList pvcs = client.persistentVolumeClaims()
    .withField("spec.storageClassName", "fast-ssd")
    .list();

Service Accounts

Service account operations for pod authentication and authorization.

public interface KubernetesClient {
    MixedOperation<ServiceAccount, ServiceAccountList, ServiceAccountResource> serviceAccounts();
}

Usage Examples:

// Create a service account
ServiceAccount sa = client.serviceAccounts().create(new ServiceAccountBuilder()
    .withNewMetadata()
        .withName("app-service-account")
    .endMetadata()
    .build());

// Create service account with image pull secrets
ServiceAccount saWithSecrets = client.serviceAccounts().create(new ServiceAccountBuilder()
    .withNewMetadata()
        .withName("app-sa-with-secrets")
    .endMetadata()
    .addNewImagePullSecret()
        .withName("registry-secret")
    .endImagePullSecret()
    .build());

Resource Builder Patterns

All Kubernetes resources support builder patterns for fluent creation and modification:

// Pod builder example
Pod pod = new PodBuilder()
    .withNewMetadata()
        .withName("example-pod")
        .withNamespace("default")
        .addToLabels("app", "example")
        .addToAnnotations("description", "Example pod")
    .endMetadata()
    .withNewSpec()
        .addNewContainer()
            .withName("main")
            .withImage("nginx:1.21")
            .addNewPort()
                .withContainerPort(80)
                .withName("http")
            .endPort()
            .addNewEnv()
                .withName("ENV_VAR")
                .withValue("example-value")
            .endEnv()
            .withNewResources()
                .addToRequests("cpu", new Quantity("100m"))
                .addToRequests("memory", new Quantity("128Mi"))
                .addToLimits("cpu", new Quantity("500m"))
                .addToLimits("memory", new Quantity("512Mi"))
            .endResources()
        .endContainer()
        .withRestartPolicy("Always")
    .endSpec()
    .build();

Error Handling

Resource operations can throw various exceptions that should be handled appropriately:

try {
    Pod pod = client.pods().withName("my-pod").get();
    if (pod == null) {
        System.out.println("Pod not found");
    }
} catch (KubernetesClientException e) {
    if (e.getCode() == 404) {
        System.out.println("Pod not found: " + e.getMessage());
    } else if (e.getCode() == 403) {
        System.out.println("Access denied: " + e.getMessage());
    } else {
        System.out.println("API error: " + e.getMessage());
    }
}

// Using require() method that throws exception if resource not found
try {
    Pod pod = client.pods().withName("my-pod").require();
    // Pod is guaranteed to exist here
} catch (ResourceNotFoundException e) {
    System.out.println("Required pod not found: " + e.getMessage());
}

Install with Tessl CLI

npx tessl i tessl/maven-io-fabric8--kubernetes-client

docs

api-groups.md

client-configuration.md

core-resources.md

custom-resources.md

exception-handling.md

index.md

pod-operations.md

utilities.md

watch-informers.md

tile.json