使用java使用fabric.io获取当前部署名称

问题描述 投票:0回答:1

我正在尝试在使用 Fabric.io 时获取当前的命名空间和部署名称。

对于命名空间,我使用:k8sClient.getConfiguration().getNamespace()

知道我应该使用什么来获取当前部署名称吗?

我正在使用特定的部署名称部署我的代码(使用 Pod),例如:“helm install myDeploymentName .”我需要获取名称:“myDeploymentName

java kubernetes fabric8 fabric8-kubernetes-client
1个回答
0
投票
  • 通常 pod 名称写为
    /etc/hostname
  • 您可以依靠 Kubernetes Downward API 将 pod 信息公开到环境变量或文件(参见示例此处)。

您可以通过上述任一方法使用此名称来获取 pod,并从

.metadata.ownerReferences
获取所有者 ReplicaSet 的名称。然后从 ReplicaSet 的
.metadata.ownerReferences

获取找到的 ReplicaSet 的所有者 Deployment

这里是一些使用方法 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);
    }
© www.soinside.com 2019 - 2024. All rights reserved.