java操作k8s-Api(fabric8)
-
- k8s资源文件路径
- [k8s maven依赖](#k8s maven依赖)
- 访问k8s-api的几种方式
k8s资源文件路径
默认k8s的配置文件在/etc/kubernetes目录下
k8s maven依赖
XML
<dependency>
<groupId>io.fabric8</groupId>
<artifactId>kubernetes-client</artifactId>
<version>6.10.0</version>
</dependency>
访问k8s-api的几种方式
通过配置文件访问
java
//可以放在resource下,通过配置获取admin.conf
Resource adminConf = k8sInfoConfig.getAdminConf();
String adminConfStr = IOUtils.toString(adminConf.getInputStream());
Config config = Config.fromKubeconfig(adminConfStr);
//sourceK8s.getApiServer() 获取的是k8s地址端口,默认为ip:6443端口
config.setMasterUrl(sourceK8s.getApiServer());
KubernetesClient client = new DefaultKubernetesClient(config);
通过证书访问
证书包括三点: certificate-authority-data、client-certificate-data、 client-key-data。
withCaCertData: certificate-authority-data
withClientCertData: client-certificate-data
withClientKeyData: client-key-data
java
ConfigBuilder builder = new ConfigBuilder();
builder.withMasterUrl(sourceK8s.getApiServer());
//客户端访问需要证书,此三项参数不可缺少
builder.withCaCertData(sourceK8s.getCaCertData());
builder.withClientCertData(sourceK8s.getClientCertData());
builder.withClientKeyData(sourceK8s.getClientKeyData());
Config config = builder.build();
KubernetesClient client = new DefaultKubernetesClient(config);
如果证书访问被拒绝,因为令牌被再次进行了加密,第一次时可以拿到加密前的令牌,后面就拿不到了,需要问问运维哦
java访问k8s报错
通过(serviceAccount)sa-token访问
pod在启动时,每个pod都会分配一个serviceAccount,如果没有配置,则分配default的serviceAccount。(这里我只启动了一个deployment绑定了serviceAccount获取到了token,就能够访问k8s了)
默认default用户没有权限访问deployment等权限。所以新建serviceAccount,创建用户绑定cluster-admin(可换,具体有哪些用户百度一下)权限。
以下执行:kubectl apply -f xxx.yaml
powershell
apiVersion: v1
kind: ServiceAccount
metadata:
name: kubepi-user
namespace: spas
用户角色权限绑定
powershell
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: kubepi-user
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cluster-admin
subjects:
- kind: ServiceAccount
name: kubepi-user
namespace: spas
其中spas为集群存在namespace。
创建deployment(pod)绑定serviceAccount:
获取token,mtac-c59b65fd6-ncd9j为pod名称,默认是在/run/secrets/kubernetes.io/serviceaccount/token,可以看看官网。
powershell
kubectl -n spas exec -it mtac-c59b65fd6-ncd9j -- cat /run/secrets/kubernetes.io/serviceaccount/token
获取token后:
java
String tokenStr = k8sInfoConfig.getTokenStr();//这就是获取到的token,替换一下
Config build = new ConfigBuilder().withMasterUrl(sourceK8s.getApiServer()).withTrustCerts(true).withOauthToken(tokenStr).build();
KubernetesClient client = new DefaultKubernetesClient(build);