Cloud Native 14 min read

Master Kubernetes ReplicationController, ConfigMap, and Secret with Java Client

This guide demonstrates how to use the Fabric8 Kubernetes Java client to load, create, retrieve, update, scale, watch, and delete ReplicationController, ConfigMap, and Secret resources, providing complete code examples and step‑by‑step commands for managing these objects across namespaces in a Kubernetes cluster.

FunTester
FunTester
FunTester
Master Kubernetes ReplicationController, ConfigMap, and Secret with Java Client

Kubernetes provides three core resource types for managing application configuration and state: ReplicationController (an early controller replaced by ReplicaSet), ConfigMap (for non‑sensitive configuration data), and Secret (for sensitive data such as passwords and tokens). All three can be accessed through the Fabric8 Java client via client.replicationControllers(), client.configMaps(), and client.secrets().

ReplicationController Operations

Load a ReplicationController from a YAML file

ReplicationController aReplicationController = client.replicationControllers()
    .inNamespace("default")
    .load(new FileInputStream("/test-replicationcontroller.yml"))
    .item();

Get a ReplicationController from the API server

ReplicationController rc = client.replicationControllers()
    .inNamespace("default")
    .withName("nginx-controller")
    .get();

Create a new ReplicationController

ReplicationController rc1 = new ReplicationControllerBuilder()
    .withNewMetadata().withName("nginx-controller").addToLabels("server", "nginx").endMetadata()
    .withNewSpec().withReplicas(3)
    .withNewTemplate()
        .withNewMetadata().addToLabels("server", "nginx").endMetadata()
        .withNewSpec()
            .addNewContainer().withName("nginx").withImage("nginx")
                .addNewPort().withContainerPort(80).endPort()
            .endContainer()
        .endSpec()
    .endTemplate()
    .endSpec()
    .build();
client.replicationControllers().inNamespace("default").resource(rc1).create();

Server‑side apply a ReplicationController

client.replicationControllers().inNamespace("default").resource(rc1).serverSideApply();

List ReplicationControllers in a specific namespace

ReplicationControllerList rcList = client.replicationControllers()
    .inNamespace("default")
    .list();

List all ReplicationControllers across namespaces

ReplicationControllerList rcList = client.replicationControllers()
    .inAnyNamespace()
    .list();

List ReplicationControllers with a specific label

ReplicationControllerList rcList = client.replicationControllers()
    .inNamespace("default")
    .withLabel("foo", "bar")
    .list();

Delete a ReplicationController

client.replicationControllers()
    .inNamespace("default")
    .withName("nginx-controller")
    .delete();

Watch ReplicationController events

client.replicationControllers()
    .inNamespace(currentNamespace)
    .watch(new Watcher<>() {
        @Override
        public void eventReceived(Action action, ReplicationController resource) {
            // Handle event based on action type
        }
        @Override
        public void onClose(WatcherException cause) {
            // Cleanup on watch close
        }
    });

Scale a ReplicationController

client.replicationControllers()
    .inNamespace("default")
    .withName("nginx-controller")
    .scale(2);

Update the image of a ReplicationController

client.replicationControllers()
    .inNamespace("default")
    .withName("nginx")
    .updateImage("nginx:latest");

Update multiple container images

Map<String, String> containerToImageMap = new HashMap<>();
containerToImageMap.put("c1", "image1");
containerToImageMap.put("c2", "image2");
client.replicationControllers()
    .inNamespace("default")
    .withName("nginx")
    .updateImage(containerToImageMap);

ConfigMap Operations

Load a ConfigMap from a YAML file

ConfigMap configMap = client.configMaps()
    .load(new FileInputStream("configmap1.yml"))
    .item();

Get a ConfigMap from the API server

ConfigMap configMap = client.configMaps()
    .inNamespace("default")
    .withName("configmap1")
    .get();

Create a ConfigMap

ConfigMap configMap1 = new ConfigMapBuilder()
    .withNewMetadata().withName("configmap1").endMetadata()
    .addToData("1", "one")
    .addToData("2", "two")
    .addToData("3", "three")
    .build();
client.configMaps().inNamespace("default").resource(configMap1).create();

Server‑side apply a ConfigMap

client.configMaps()
    .inNamespace("default")
    .resource(configMap1)
    .serverSideApply();

List ConfigMaps in a namespace

ConfigMapList configMapList = client.configMaps()
    .inNamespace("default")
    .list();

List all ConfigMaps across namespaces

ConfigMapList configMapList = client.configMaps()
    .inAnyNamespace()
    .list();

List ConfigMaps by label

ConfigMapList configMapList = client.configMaps()
    .inNamespace("default")
    .withLabel("foo", "bar")
    .list();

Delete a ConfigMap

client.configMaps()
    .inNamespace("default")
    .withName("configmap1")
    .delete();

Watch ConfigMap events

client.configMaps()
    .inNamespace("default")
    .watch(new Watcher<>() {
        @Override
        public void eventReceived(Action action, ConfigMap resource) {
            // Handle event based on action type
        }
        @Override
        public void onClose(WatcherException cause) {
            // Cleanup on watch close
        }
    });

Edit a ConfigMap

ConfigMap configMap1 = client.configMaps()
    .inNamespace(currentNamespace)
    .withName("configmap1")
    .edit(c -> new ConfigMapBuilder(c)
        .addToData("4", "four")
        .build());

Secret Operations

Load a Secret from a YAML file

Secret aSecret = client.secrets()
    .inNamespace("default")
    .load(new FileInputStream("test-secret.yml"))
    .item();

Get a Secret from the API server

Secret secret = client.secrets()
    .inNamespace("default")
    .withName("secret1")
    .get();

Create a Secret (Base64‑encoded data)

Secret secret1 = new SecretBuilder()
    .withNewMetadata().withName("secret1").endMetadata()
    .addToData("username", "dXNlcm5hbWU=") // "username" in Base64
    .addToData("password", "cGFzc3dvcmQ=") // "password" in Base64
    .build();
client.secrets().inNamespace("default").resource(secret1).create();

Server‑side apply a Secret

client.secrets()
    .inNamespace("default")
    .resource(secret1)
    .serverSideApply();

List Secrets in a namespace

SecretList secretList = client.secrets()
    .inNamespace("default")
    .list();

List all Secrets across namespaces

SecretList secretList = client.secrets()
    .inAnyNamespace()
    .list();

List Secrets by label

SecretList secretList = client.secrets()
    .inNamespace("default")
    .withLabel("foo", "bar")
    .list();

Edit a Secret

Secret secret1 = client.secrets()
    .inNamespace(currentNamespace)
    .withName("secret1")
    .edit(s -> new SecretBuilder(s)
        .withType("Opaque")
        .build());

Delete a Secret

client.secrets()
    .inNamespace("default")
    .withName("secret1")
    .delete();

Watch Secret events

client.secrets()
    .inNamespace("default")
    .watch(new Watcher<>() {
        @Override
        public void eventReceived(Action action, Secret resource) {
            // Handle event based on action type
        }
        @Override
        public void onClose(WatcherException cause) {
            // Cleanup on watch close
        }
    });

Complete Example Program

import io.fabric8.kubernetes.api.model.*;
import io.fabric8.kubernetes.api.model.apps.ReplicationController;
import io.fabric8.kubernetes.api.model.apps.ReplicationControllerBuilder;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.Watcher;
import io.fabric8.kubernetes.client.WatcherException;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;

public class KubernetesResourceExample {
    public static void main(String[] args) throws Exception {
        try (KubernetesClient client = new DefaultKubernetesClient()) {
            String namespace = "default";

            // 1. Create ReplicationController
            ReplicationController rc = new ReplicationControllerBuilder()
                .withNewMetadata().withName("fun-tester-rc").endMetadata()
                .withNewSpec().withReplicas(2)
                .withNewTemplate()
                    .withNewMetadata().addToLabels("app", "fun-tester").endMetadata()
                    .withNewSpec()
                        .addNewContainer()
                            .withName("fun-tester-container")
                            .withImage("nginx:latest")
                            .addNewPort().withContainerPort(80).endPort()
                        .endContainer()
                    .endSpec()
                .endTemplate()
                .endSpec()
                .build();
            client.replicationControllers().inNamespace(namespace).resource(rc).create();
            System.out.println("ReplicationController created successfully!");

            // 2. Retrieve ReplicationController
            ReplicationController fetchedRc = client.replicationControllers()
                .inNamespace(namespace)
                .withName("fun-tester-rc")
                .get();
            System.out.println("Fetched ReplicationController: " + fetchedRc.getMetadata().getName());

            // 3. Scale ReplicationController
            client.replicationControllers()
                .inNamespace(namespace)
                .withName("fun-tester-rc")
                .scale(3);
            System.out.println("ReplicationController scaled to 3 replicas");

            // 4. Create ConfigMap
            ConfigMap configMap = new ConfigMapBuilder()
                .withNewMetadata().withName("fun-tester-config").endMetadata()
                .addToData("key1", "value1")
                .addToData("key2", "value2")
                .build();
            client.configMaps().inNamespace(namespace).resource(configMap).create();
            System.out.println("ConfigMap created successfully!");

            // 5. Retrieve ConfigMap
            ConfigMap fetchedConfigMap = client.configMaps()
                .inNamespace(namespace)
                .withName("fun-tester-config")
                .get();
            System.out.println("Fetched ConfigMap data: " + fetchedConfigMap.getData());

            // 6. Create Secret (Base64 encoded values)
            Secret secret = new SecretBuilder()
                .withNewMetadata().withName("fun-tester-secret").endMetadata()
                .addToData("username", "dXNlcm5hbWU=") // "username"
                .addToData("password", "cGFzc3dvcmQ=") // "password"
                .build();
            client.secrets().inNamespace(namespace).resource(secret).create();
            System.out.println("Secret created successfully!");

            // 7. Retrieve Secret
            Secret fetchedSecret = client.secrets()
                .inNamespace(namespace)
                .withName("fun-tester-secret")
                .get();
            System.out.println("Fetched Secret data: " + fetchedSecret.getData());

            // 8. Watch ReplicationController events
            client.replicationControllers().inNamespace(namespace).watch(new Watcher<>() {
                @Override
                public void eventReceived(Action action, ReplicationController resource) {
                    System.out.println("ReplicationController event: " + action + " - " + resource.getMetadata().getName());
                }
                @Override
                public void onClose(WatcherException cause) {
                    System.out.println("Watch closed: " + cause.getMessage());
                }
            });

            // 9. Delete resources
            client.replicationControllers().inNamespace(namespace).withName("fun-tester-rc").delete();
            System.out.println("ReplicationController deleted successfully!");
            client.configMaps().inNamespace(namespace).withName("fun-tester-config").delete();
            System.out.println("ConfigMap deleted successfully!");
            client.secrets().inNamespace(namespace).withName("fun-tester-secret").delete();
            System.out.println("Secret deleted successfully!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Sample Output

ReplicationController created successfully!
Fetched ReplicationController: fun-tester-rc
ReplicationController scaled to 3 replicas
ConfigMap created successfully!
Fetched ConfigMap data: {key1=value1, key2=value2}
Secret created successfully!
Fetched Secret data: {username=dXNlcm5hbWU=, password=cGFzc3dvcmQ=}
ReplicationController event: ADDED - fun-tester-rc
ReplicationController deleted successfully!
ConfigMap deleted successfully!
Secret deleted successfully!

By following these examples, you can confidently manage ReplicationController, ConfigMap, and Secret resources in a Kubernetes cluster using the Java client, streamlining configuration handling and resource lifecycle operations for testing or production workloads.

JavaKubernetesConfigMapFabric8SecretReplicationControllerKubernetesClient
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.