使用https访问kubernetes的方式
本文介绍三种使用https协议访问kubernetes集群的方式:(1)curl (2) fabric8 API(3) 使用Rest API
kubernetes集群的生成的安全认证文件
apiserver.crt apiserver.key
ca.crt ca.key ca.srl
server.crt server.csr server.key
curl访问kubernetes
将kubernetes集群的认证文件拷贝到要访问kubernetes集群的机器上
例如:拷贝到/root/kubernetes
cd /root/kubernetes
curl -k --cert ./server.crt --key ./server.key -X GET https://192.168.1.100:6443/api/v1/nodes
fabric8 API访问kubernetes集群
public class Fabric8ioAPITest {
private KubernetesClient client;
@Before
public void connectTest(){
Config config = new ConfigBuilder().withMasterUrl("https://192.168.1.100:6443")
.withTrustCerts(true)
.withCaCertFile(Thread.currentThread().getContextClassLoader().getResource("").getPath()+"k8s/product/ca.crt")
.withClientCertFile(Thread.currentThread().getContextClassLoader().getResource("").getPath()+"k8s/product/server.crt")
.withClientKeyFile(Thread.currentThread().getContextClassLoader().getResource("").getPath()+"k8s/product/server.key")
.build();
client = new DefaultKubernetesClient(config);
}
@Test
public void listDeploymentTest(){
DeploymentList list = client.extensions().deployments().list();
for(Deployment deployment:list.getItems()){
System.out.println(deployment.getMetadata().getName());
}
}
}
使用Rest API访问kubernetes集群
kubernetes-client 的2.2.7版本目前没有提供访问statefulset的功能,所以需要使用Rest API来操作
public class KubernetesRestAPITest {
@Test
public void testk8s(){
Config config = new ConfigBuilder().withMasterUrl("https://192.168.1.100:6443")
.withTrustCerts(true)
.withCaCertFile(Thread.currentThread().getContextClassLoader().getResource("").getPath()+"k8s/staging/ca.crt")
.withClientCertFile(Thread.currentThread().getContextClassLoader().getResource("").getPath()+"k8s/staging/server.crt")
.withClientKeyFile(Thread.currentThread().getContextClassLoader().getResource("").getPath()+"k8s/staging/server.key")
.build();
OkHttpClient k8sClient=HttpClientUtils.createHttpClient(config);
Request k8sRequest = new Request.Builder().url("https://192.168.1.100:6443/apis/apps/v1beta1/namespaces/default/statefulsets/").build();
Call call = k8sClient.newCall(k8sRequest);
try {
Response k8sresponse = call.execute();
System.out.println(k8sresponse.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
网友评论