java操作k8s api

使用kubernetes-client/java类库,实现java对k8s api的调用

新建maven项目,引入依赖

我的k8s版本是1.5的,所以引入7.0.0的版本

    
        
            io.kubernetes
            client-java
            7.0.0
            compile
        
    

将k8s的config文件复制到项目下

通过ftp把~/.kube/config下载下来放到项目下面。


ftp

config

新建一个测试文件

import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1Pod;
import io.kubernetes.client.openapi.models.V1PodList;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.KubeConfig;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class TestClient {
    public static void main(String[] args) throws ApiException, IOException, ApiException {
        //直接写config path
        String kubeConfigPath = "config";

        //加载k8s, config
        ApiClient client = ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath))).build();

        //将加载config的client设置为默认的client
        Configuration.setDefaultApiClient(client);

        //创建一个api
        CoreV1Api api = new CoreV1Api();

        //打印所有的pod
        V1PodList list = api.listPodForAllNamespaces(null,null,null,null,null,null,null,
        null,null);

        for (V1Pod item : list.getItems()) {
            System.out.println(item);
        }
    }
}

你可能感兴趣的:(java操作k8s api)