写点什么

Fabric8 Kubernetes 教程——PVC、PV、Network、PDB、Role、Cluster

作者:FunTester
  • 2025-03-30
    河北
  • 本文字数:8519 字

    阅读完需:约 28 分钟

EndpointSlice

EndpointSlice 是 Kubernetes 中用于扩展和优化 Endpoints 功能的一种资源对象。它是对传统 Endpoints 的改进,主要用于更高效地管理和存储服务后端的端点信息。


EndpointSlice 资源可以通过 client.discovery().v1().endpointSlices() 访问。

从 YAML 文件加载 EndpointSlice

EndpointSlice es = client.discovery().v1().endpointSlices()  .load(getClass().getResourceAsStream("/endpointslice.yml")).item();
复制代码

从 Kubernetes API 服务器获取 EndpointSlice

EndpointSlice esFromServer = client.discovery().v1().endpointSlices()  .inNamespace("default").withName("es1").get();
复制代码

创建 EndpointSlice

EndpointSlice esToCreate = new EndpointSliceBuilder()  .withNewMetadata()  .withName(name)  .addToLabels("kubernetes.io/service-name", "example")  .endMetadata()  .withAddressType("IPv4")  .addNewPort()  .withName("http")  .withPort(80)  .endPort()  .addNewEndpoint()  .withAddresses("10.1.2.3")  .withNewConditions().withReady(true).endConditions()  .withHostname("pod-1")  .addToTopology("kubernetes.io/hostname", "node-1")  .addToTopology("topology.kubernetes.io/zone", "us-west2-a")  .endEndpoint()  .build();esToCreate = client.discovery().v1().endpointSlices().inNamespace("ns1").resource(esToCreate).create();
复制代码

将 EndpointSlice 应用到 Kubernetes 集群

EndpointSlice es = client.discovery().v1().endpointSlices().inNamespace("ns1").resource(endpointSlice).serverSideApply();
复制代码

列出某个命名空间中的 EndpointSlice

EndpointSliceList esList = client.discovery().v1().endpointSlices().inNamespace("default").list();
复制代码

列出所有命名空间中的 EndpointSlice

EndpointSliceList esList = client.discovery().v1().endpointSlices().inAnyNamespace().list();
复制代码

列出具有某些标签的 EndpointSlice

EndpointSliceList esList = client.discovery().v1().endpointSlices().inNamespace("default").withLabel("foo", "bar").list();
复制代码

删除 EndpointSlice

client.discovery().v1().endpointSlices().inNamespace("default").withName("test-es").delete();
复制代码

监听 EndpointSlice

client.discovery().v1().endpointSlices().inNamespace("default").watch(new Watcher<>() {  @Override  public void eventReceived(Action action, EndpointSlice resource) {    // 根据操作类型执行某些操作  }
@Override public void onClose(WatcherException cause) { // 处理关闭事件 }});
复制代码

PersistentVolumeClaim

PersistentVolumeClaim (PVC) 是 Kubernetes 中用户对存储资源的请求,用于动态绑定 PersistentVolume (PV),为 Pod 提供持久化存储。


PersistentVolumeClaim 可以通过 client.persistentVolumeClaims() 访问。

从 YAML 文件加载 PersistentVolumeClaim

PersistentVolumeClaim pvc = client.persistentVolumeClaims().load(new FileInputStream("pvc.yaml")).item();
复制代码

从 Kubernetes API 服务器获取 PersistentVolumeClaim

PersistentVolumeClaim pvc = client.persistentVolumeClaims().inNamespace("default").withName("test-pv-claim").get();
复制代码

创建 PersistentVolumeClaim

PersistentVolumeClaim persistentVolumeClaim = new PersistentVolumeClaimBuilder()  .withNewMetadata().withName("test-pv-claim").endMetadata()  .withNewSpec()  .withStorageClassName("my-local-storage")  .withAccessModes("ReadWriteOnce")  .withNewResources()  .addToRequests("storage", new Quantity("500Gi"))  .endResources()  .endSpec()  .build();
client.persistentVolumeClaims().inNamespace("default").resource(persistentVolumeClaim).create();
复制代码

将 PersistentVolumeClaim 应用到 Kubernetes 集群

PersistentVolumeClaim pvc = client.persistentVolumeClaims().inNamespace("default").resource(pvcToCreate).serverSideApply();
复制代码

列出某个命名空间中的 PersistentVolumeClaim

PersistentVolumeClaimList pvcList = client.persistentVolumeClaims().inNamespace("default").list();
复制代码

列出所有命名空间中的 PersistentVolumeClaim

PersistentVolumeClaimList pvcList = client.persistentVolumeClaims().inAnyNamespace().list();
复制代码

列出具有某些标签的 PersistentVolumeClaim

PersistentVolumeClaimList pvcList = client.persistentVolumeClaims().inNamespace("default").withLabel("foo", "bar").list();
复制代码

删除 PersistentVolumeClaim

client.persistentVolumeClaims().inNamespace("default").withName("test-pv-claim").delete();
复制代码

PersistentVolume

PersistentVolume (PV) 是 Kubernetes 中由管理员提供的存储资源,代表集群中的一块持久化存储,可供 Pod 通过 PersistentVolumeClaim (PVC) 绑定和使用。


PersistentVolume 资源可以通过 client.persistentVolumes() 访问。

从 YAML 文件加载 PersistentVolume

PersistentVolume pv = client.persistentVolumes().load(new FileInputStream("pv.yaml")).item();
复制代码

从 Kubernetes API 服务器获取 PersistentVolume

PersistentVolume pv = client.persistentVolumes().withName("test-local-pv").get();
复制代码

创建 PersistentVolume

PersistentVolume pv = new PersistentVolumeBuilder()  .withNewMetadata().withName("test-local-pv").endMetadata()  .withNewSpec()  .addToCapacity(Collections.singletonMap("storage", new Quantity("500Gi")))  .withAccessModes("ReadWriteOnce")  .withPersistentVolumeReclaimPolicy("Retain")  .withStorageClassName("my-local-storage")  .withNewLocal()  .withPath("/mnt/disks/vol1")  .endLocal()  .withNewNodeAffinity()  .withNewRequired()  .addNewNodeSelectorTerm()  .withMatchExpressions(Arrays.asList(new NodeSelectorRequirementBuilder()    .withKey("kubernetes.io/hostname")    .withOperator("In")    .withValues("my-node")    .build()  ))  .endNodeSelectorTerm()  .endRequired()  .endNodeAffinity()  .endSpec()  .build();
PersistentVolume pvCreated = client.persistentVolumes().resource(pv).create();
复制代码

将 PersistentVolume 应用到 Kubernetes 集群

PersistentVolume pv = client.persistentVolumes().resource(pvToCreate).serverSideApply();
复制代码

列出 PersistentVolume

PersistentVolumeList pvList = client.persistentVolumes().list();
复制代码

列出具有某些标签的 PersistentVolume

PersistentVolumeList pvList = client.persistentVolumes().withLabel("foo", "bar").list();
复制代码

删除 PersistentVolume

client.persistentVolumes().withName("test-local-pv").delete();
复制代码

NetworkPolicy

NetworkPolicy 是 Kubernetes 中用于定义 Pod 之间网络通信规则的对象,通过标签选择器控制入站和出站流量,实现网络隔离和安全策略。


NetworkPolicy 可以通过 client.network().networkPolicies() 访问。

从 YAML 文件加载 NetworkPolicy

NetworkPolicy loadedNetworkPolicy = client.network().networkPolicies()  .load(new FileInputStream("/test-networkpolicy.yml")).item();
复制代码

从 Kubernetes API 服务器获取 NetworkPolicy

NetworkPolicy getNetworkPolicy = client.network().networkPolicies()  .withName("networkpolicy").get();
复制代码

创建 NetworkPolicy

NetworkPolicy networkPolicy = new NetworkPolicyBuilder()  .withNewMetadata()  .withName("networkpolicy")  .addToLabels("foo","bar")  .endMetadata()  .withNewSpec()  .withNewPodSelector()  .addToMatchLabels("role","db")  .endPodSelector()  .addToIngress(0,    new NetworkPolicyIngressRuleBuilder()    .addToFrom(0, new NetworkPolicyPeerBuilder().withNewPodSelector()      .addToMatchLabels("role","frontend").endPodSelector()      .build()    ).addToFrom(1, new NetworkPolicyPeerBuilder().withNewNamespaceSelector()      .addToMatchLabels("project","myproject").endNamespaceSelector()      .build()    )    .addToPorts(0,new NetworkPolicyPortBuilder().withPort(new IntOrString(6379))      .withProtocol("TCP").build())    .build()  )  .endSpec()  .build();
NetworkPolicy npCreated = client.network().networkPolicies().resource(networkPolicy).create();
复制代码

将 NetworkPolicy 应用到 Kubernetes 集群

NetworkPolicy npCreated = client.network().networkPolicies().resource(networkPolicy).serverSideApply();
复制代码

列出 NetworkPolicy

NetworkPolicyList networkPolicyList = client.network().networkPolicies().list();
复制代码

列出具有某些标签的 NetworkPolicy

NetworkPolicyList networkPolicyList = client.network().networkPolicies()  .withLabels(Collections.singletonMap("foo","bar")).list();
复制代码

删除 NetworkPolicy

client.network().networkPolicies().withName("np-test").delete();
复制代码

PodDisruptionBudget

PodDisruptionBudget (PDB) 是 Kubernetes 中用于限制自愿中断(如升级或维护)时 Pod 的最大不可用数量或最小可用数量,确保应用的高可用性。


PodDisruptionBudget 可以通过 client.policy().v1().podDisruptionBudget() 访问。

从 YAML 文件加载 PodDisruptionBudget

PodDisruptionBudget pdb = client.policy().v1().podDisruptionBudget().load(new FileInputStream("/test-pdb.yml")).item();
复制代码

从 Kubernetes API 服务器获取 PodDisruptionBudget

PodDisruptionBudget podDisruptionBudget = client.policy().v1().podDisruptionBudget().inNamespace("default").withName("poddisruptionbudget1").get();
复制代码

创建 PodDisruptionBudget

PodDisruptionBudget podDisruptionBudget = new PodDisruptionBudgetBuilder()  .withNewMetadata().withName("zk-pkb").endMetadata()  .withNewSpec()  .withMaxUnavailable(new IntOrString("1%"))  .withNewSelector()  .withMatchLabels(Collections.singletonMap("app", "zookeeper"))  .endSelector()  .endSpec()  .build();
client.policy().v1().podDisruptionBudget().inNamespace("default").resource(podDisruptionBudget).create();
复制代码

将 PodDisruptionBudget 应用到 Kubernetes 集群

PodDisruptionBudget pdb = client.policy().v1().podDisruptionBudget().inNamespace("default").resource(podDisruptionBudgetObj).serverSideApply();
复制代码

列出某个命名空间中的 PodDisruptionBudget

PodDisruptionBudgetList podDisruptionBudgetList = client.policy().v1().podDisruptionBudget().inNamespace("default").list();
复制代码

列出所有命名空间中的 PodDisruptionBudget

PodDisruptionBudgetList pdbList = client.policy().v1().podDisruptionBudget().inAnyNamespace().list();
复制代码

列出具有某些标签的 PodDisruptionBudget

PodDisruptionBudgetList pdbList = client.policy().v1().podDisruptionBudget().inNamespace("default").withLabel("foo", "bar").list();
复制代码

删除 PodDisruptionBudget

client.policy().v1().podDisruptionBudget().inNamespace("default").withName("poddisruptionbudget1").delete();
复制代码

SelfSubjectAccessReview

创建 SelfSubjectAccessReview

try (KubernetesClient client = new KubernetesClientBuilder().build()) {  SelfSubjectAccessReview ssar = new SelfSubjectAccessReviewBuilder()    .withNewSpec()    .withNewResourceAttributes()    .withGroup("apps")    .withResource("deployments")    .withVerb("create")    .withNamespace("dev")    .endResourceAttributes()    .endSpec()    .build();
ssar = client.authorization().v1().selfSubjectAccessReview().create(ssar); System.out.println("Allowed: " + ssar.getStatus().getAllowed());}
复制代码

SubjectAccessReview

创建 SubjectAccessReview

try (KubernetesClient client = new KubernetesClientBuilder().build()) {  SubjectAccessReview sar = new SubjectAccessReviewBuilder()    .withNewSpec()    .withNewResourceAttributes()    .withGroup("apps")    .withResource("deployments")    .withVerb("create")    .withNamespace("default")    .endResourceAttributes()    .withUser("kubeadmin")    .endSpec()    .build();
sar = client.authorization().v1().subjectAccessReview().create(sar); System.out.println("Allowed: " + sar.getStatus().getAllowed());}
复制代码

LocalSubjectAccessReview

创建 LocalSubjectAccessReview

try (KubernetesClient client = new KubernetesClientBuilder().build()) {  LocalSubjectAccessReview lsar = new LocalSubjectAccessReviewBuilder()    .withNewMetadata().withNamespace("default").endMetadata()    .withNewSpec()    .withUser("foo")    .withNewResourceAttributes()    .withNamespace("default")    .withVerb("get")    .withGroup("apps")    .withResource("pods")    .endResourceAttributes()    .endSpec()    .build();  lsar = client.authorization().v1().localSubjectAccessReview().inNamespace("default").create(lsar);  System.out.println(lsar.getStatus().getAllowed());}
复制代码

SelfSubjectRulesReview

创建 SelfSubjectRulesReview

try (KubernetesClient client = new KubernetesClientBuilder().build()) {  SelfSubjectRulesReview selfSubjectRulesReview = new SelfSubjectRulesReviewBuilder()    .withNewMetadata().withName("foo").endMetadata()    .withNewSpec()    .withNamespace("default")    .endSpec()    .build();
selfSubjectRulesReview = client.authorization().v1().selfSubjectRulesReview().create(selfSubjectRulesReview); System.out.println(selfSubjectRulesReview.getStatus().getIncomplete()); System.out.println("Non-resource rules: " + selfSubjectRulesReview.getStatus().getNonResourceRules().size()); System.out.println("Resource rules: " + selfSubjectRulesReview.getStatus().getResourceRules().size());}
复制代码

ClusterRole

ClusterRole 是 Kubernetes 中定义集群范围内权限的对象,用于授予对集群资源(如节点、命名空间等)的访问权限,通常与 ClusterRoleBinding 结合使用。


ClusterRole 可以通过 client.rbac().clusterRoles() 访问。

从 YAML 文件加载 ClusterRole

ClusterRole clusterRole = client.rbac().clusterRoles().load(new FileInputStream("clusterroles-test.yml")).item();
复制代码

从 Kubernetes API 服务器获取 ClusterRole

ClusterRole clusterRole = client.rbac().clusterRoles().withName("clusterrole1").get();
复制代码

列出 ClusterRole

ClusterRoleList clusterRoleList = client.rbac().clusterRoles().list();
复制代码

列出具有某些标签的 ClusterRole

ClusterRoleList clusterRoleList = client.rbac().clusterRoles().withLabel("key1", "value1").list();
复制代码

删除 ClusterRole

client.rbac().clusterRoles().withName("clusterrole1").delete();
复制代码

ClusterRoleBinding

ClusterRoleBinding 可以通过 client.rbac().clusterRoleBindings() 访问。

从 YAML 文件加载 ClusterRoleBinding

ClusterRoleBinding clusterRoleBinding = client.rbac().clusterRoleBindings().load(new FileInputStream("clusterrolebinding-test.yml")).item();
复制代码

从 Kubernetes API 服务器创建 ClusterRoleBinding

List<Subject> subjects = new ArrayList<>();Subject subject = new Subject();subject.setKind("ServiceAccount");subject.setName("serviceaccountname");subject.setNamespace("default");subjects.add(subject);
RoleRef roleRef = new RoleRef();roleRef.setApiGroup("rbac.authorization.k8s.io");roleRef.setKind("ClusterRole");roleRef.setName("clusterrolename");
ClusterRoleBinding clusterRoleBindingCreated = new ClusterRoleBindingBuilder() .withNewMetadata().withName("clusterrolebindingname").withNamespace("default").endMetadata() .withRoleRef(roleRef) .addAllToSubjects(subjects) .build();
ClusterRoleBinding clusterRoleBinding = client.rbac().clusterRoleBindings().resource(clusterRoleBindingCreated).create();
复制代码

从 Kubernetes API 服务器获取 ClusterRoleBinding

ClusterRoleBinding clusterRoleBinding = client.rbac().clusterRoleBindings().withName("clusterrolebindingname").get();
复制代码

列出 ClusterRoleBinding

ClusterRoleBindingList clusterRoleBindingList = client.rbac().clusterRoleBindings().list();
复制代码

列出具有某些标签的 ClusterRoleBinding

ClusterRoleBindingList clusterRoleBindingList = client.rbac().clusterRoleBindings().withLabel("key1", "value1").list();
复制代码

删除 ClusterRoleBinding

client.rbac().clusterRoleBindings().withName("clusterrolebindingname").delete();
复制代码

Role

Role 可以通过 client.rbac().roles() 访问。以下是一些常见的 Role 使用示例:


  • 从 yaml 文件加载 Role


Role role = client.rbac().roles().load(new FileInputStream("FunTester-role.yml")).item();
复制代码


  • 从 Kubernetes API 服务器创建 Role


List<PolicyRule> policyRuleList = new ArrayList<>();PolicyRule endpoints = new PolicyRule();endpoints.setApiGroups(Arrays.asList(""));endpoints.setResources(Arrays.asList("FunTester"));endpoints.setVerbs(Arrays.asList("get", "list", "watch", "create", "update", "patch"));policyRuleList.add(endpoints);Role roleCreated = new RoleBuilder()    .withNewMetadata().withName("FunTester-role").withNamespace("default").endMetadata()    .addAllToRules(policyRuleList)    .build();Role role = client.rbac().roles().resource(roleCreated).create();
复制代码

从 Kubernetes API 服务器获取 Role

Role role = client.rbac().roles().inNamespace("default").withName("FunTester-role").get();
复制代码

列出 Role 对象:

RoleList roleList = client.rbac().roles().inNamespace("default").list();
复制代码

列出具有某些标签的 Role 对象:

RoleList roleList = client.rbac().roles().inNamespace("default").withLabel("FunTester-key", "FunTester-value").list();
复制代码

删除 Role 对象:

client.rbac().roles().withName("FunTester-role").delete();
复制代码

RoleBinding

RoleBinding 可以通过 client.rbac().roleBindings() 访问。以下是一些常见的 RoleBinding 使用示例:


  • 从 yaml 文件加载 RoleBinding


RoleBinding roleBinding = client.rbac().roleBindings().load(new FileInputStream("FunTester-rolebinding.yml")).item();
复制代码


  • 从 Kubernetes API 服务器创建 RoleBinding


List<Subject> subjects = new ArrayList<>();Subject subject = new Subject();subject.setNamespace("default");subject.setKind("ServiceAccount");subject.setName("FunTester-serviceaccount");subjects.add(subject);RoleRef roleRef = new RoleRef();roleRef.setName("FunTester-role");roleRef.setKind("Role");roleRef.setApiGroup("rbac.authorization.k8s.io");RoleBinding roleBindingToCreate = new RoleBindingBuilder()    .withNewMetadata().withName("FunTester-rolebinding").withNamespace("default").endMetadata()    .addAllToSubjects(subjects)    .withRoleRef(roleRef)    .build();RoleBinding roleBinding = client.rbac().roleBindings().resource(roleBindingToCreate).create();
复制代码


  • 从 Kubernetes API 服务器获取 RoleBinding


RoleBinding roleBinding = client.rbac().roleBindings().inNamespace("default").withName("FunTester-rolebinding").get();
复制代码


  • 列出 RoleBinding 对象:


RoleBindingList roleBindingList = client.rbac().roleBindings().inNamespace("default").list();
复制代码


  • 列出具有某些标签的 RoleBinding 对象:


RoleBindingList roleBindingList = client.rbac().roleBindings().inNamespace("default").withLabel("FunTester-key", "FunTester-value").list();
复制代码


  • 删除 RoleBinding 对象:


client.rbac().roleBindings().inNamespace("default").withName("FunTester-rolebinding").delete();
复制代码

发布于: 刚刚阅读数: 3
用户头像

FunTester

关注

公众号:FunTester,800篇原创,欢迎关注 2020-10-20 加入

Fun·BUG挖掘机·性能征服者·头顶锅盖·Tester

评论

发布
暂无评论
Fabric8 Kubernetes 教程——PVC、PV、Network、PDB、Role、Cluster_FunTester_InfoQ写作社区