javaspring-bootkubernetesfabric8

How to override default kubernetes config file using java io.fabric8 kubernetes-client library


 import java.io.File;
 import org.springframework.util.ResourceUtils;
 import io.fabric8.kubernetes.api.model.metrics.v1beta1.NodeMetrics;
 import io.fabric8.kubernetes.api.model.metrics.v1beta1.NodeMetricsList;
 import io.fabric8.kubernetes.client.Config;
 import io.fabric8.kubernetes.client.DefaultKubernetesClient;
 import io.fabric8.kubernetes.client.KubernetesClient;

public class Tdd {

 public static void main(String[] args) throws Exception {
    
    File file=ResourceUtils.getFile("classpath:kubernetes_config");
    
    Config config=Config.autoConfigure(file.getAbsolutePath());
    
    try (KubernetesClient k8s = new DefaultKubernetesClient(config)) {

        NodeMetricsList nodeMetricsList = k8s.top().nodes().metrics();
        for (NodeMetrics nodeMetrics : nodeMetricsList.getItems()) {        
            System.out.println(nodeMetrics.getMetadata().getName());
            System.out.println(nodeMetrics.getUsage().get("cpu"));
            System.out.println(nodeMetrics.getUsage().get("memory"));
            
        }
    }

 }

}

when I try to override kubernetes config file it will not be working,
it is looking ".kube/config" file.
I have added a config file inside my project,
I want to use my customize config file.
how can I do it?


Solution

  • The Config class, which you've already found, has many setters to override specific settings; but it looks you want load config from another path. In that case, you can use fromKubeconfig method.

    File file = ResourceUtils.getFile("classpath:kubernetes_config");
        
    String kubeconfigContents = Files.readString(file.toPath());
    Config config = Config.fromKubeconfig(kubeconfigContents);
    
    try (KubernetesClient k8s = new DefaultKubernetesClient(config)) {
    
        NodeMetricsList nodeMetricsList = k8s.top().nodes().metrics();
        for (NodeMetrics nodeMetrics : nodeMetricsList.getItems()) {        
            System.out.println(nodeMetrics.getMetadata().getName());
            System.out.println(nodeMetrics.getUsage().get("cpu"));
            System.out.println(nodeMetrics.getUsage().get("memory"));
        }
    }