javakubernetesfabric8fabric8-kubernetes-client

get current deployment name using fabric.io using java


I am trying to get current namespace and deployment name while using fabric.io.

For namespace, I am using: k8sClient.getConfiguration().getNamespace()

Any idea what should I be using for getting current deployment name?

I am deploying my code(using a pod) with a certain deployment name, like: "helm install myDeploymentName ." I need to get the name: "myDeploymentName"


Solution

  • You can fetch pod by using this name from either of the above approaches and get name of owner ReplicaSet from .metadata.ownerReferences. Then get owner Deployment of found ReplicaSet from ReplicaSet's .metadata.ownerReferences

    Here is some code to get Deployment name using approach 1:

    
        public String getDeploymentName() {
            File hostName = new File("/etc/hostname");
            try {
                // Get Pod name either by reading the file or via environment variable exposed using Downward API
                String podName = new String(Files.readAllBytes(hostName.toPath()));
                Pod pod = client.pods().inNamespace("default").withName(podName).get();
                OwnerReference replicaSetOwnerRef = getControllerOwnerReference(pod);
                if (replicaSetOwnerRef != null) {
                    ReplicaSet replicaSet = client.apps().replicaSets().inNamespace("default").withName(replicaSetOwnerRef.getName()).get();
                    OwnerReference deploymentOwnerRef = getControllerOwnerReference(replicaSet);
                    if (deploymentOwnerRef != null) {
                        Deployment deployment = client.apps().deployments().inNamespace("default").withName(deploymentOwnerRef.getName()).get();
                        return deployment.getMetadata().getName();
                    }
                }
            } catch (IOException ioException) {
                // Handle exception
            }
            return null;
        }
    
        private OwnerReference getControllerOwnerReference(HasMetadata resource) {
            return resource.getMetadata().getOwnerReferences().stream()
                .filter(o -> Boolean.TRUE.equals(o.getController()))
                .findAny()
                .orElse(null);
        }