一、添加依赖
<dependency>
<groupId>io.fabric8</groupId>
<artifactId>kubernetes-client</artifactId>
<version>6.3.1</version>
</dependency>
二、通过kubectl 去k8s集群获取token
kubectl -n kube-system describe $(kubectl -n kube-system get secret -n kube-system -o name | grep namespace) | grep token
三、通过token访问k8s,使用Fabric框架
package cn.edu.tju;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodList;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.ConfigBuilder;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import java.util.List;
public class Demo01 {
private static String API_SERVER = "https://xx.xx.xx.xx:6443";
//去服务器通过kubectl 获取token
// kubectl -n kube-system describe $(kubectl -n kube-system get secret -n kube-system -o name | grep namespace) | grep token
private static String token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IlZuSzNPTk5fMFp1bDlHbk1sLXZuZVJuVjJkRUNmOFFwZ0hJRVRMVFF5RUUifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJuYW1lc3BhY2UtY29udHJvbGxlci10b2tlbi10ZmM5bCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJuYW1lc3BhY2UtY29udHJvbGxlciIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6IjIzNmEyYWFjLWEyZDktNDJkOC05ODkxLTU1YjY0YTIxYWQ0ZSIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDprdWJlLXN5c3RlbTpuYW1lc3BhY2UtY29udHJvbGxlciJ9.IwEnORYqxM_qnVnLM2pdxlbsStHXHmj96t5DF4EstXkG4FJh0q6lc68fpLd1tvi2lJuhPPFHxEoKk3PXXza9x1mobeBRs-TYW3sPxkMNBiBDmjRvhC6Ny_dWU7LWWaNIxMxb0BeaAfgXA1e1Fi5CLxivAeQDNxRJgkFz-FaXraEM5_1CaRJzBasDNmyZZBa5LhW-_PR4O7ENG_JxDPmaAzEEY7RrPNMh27oHpfRnXIv-7b9B3Dk0NzHly1SMAQbngdU_YoyRAc6mW9-lPujl4beHgthYpvemcxdmpOmaywuhVAUYxrekomfZDM_9McArlZgi9I9GCJNTqwLUW2eJHQ";
public static void main(String[] args) {
KubernetesClient client = null;
try {
Config build = new ConfigBuilder().withMasterUrl(API_SERVER)
.withTrustCerts(true)
.withOauthToken(token).build();
client = new DefaultKubernetesClient(build);
} catch (Exception e) {
e.printStackTrace();
}
PodList podList = client.pods().inNamespace("default").list();
List<Pod> itemList = podList.getItems();
itemList.stream().forEach(pod -> {
System.out.println(pod.getMetadata().getName());
});
}
}