背景说明

编写资源文件的过程中需要事先熟悉对应的语法。

解决方案

版本查看

  1. [root@cka-master ~]# kubectl api-versions
  2. admissionregistration.k8s.io/v1
  3. apiextensions.k8s.io/v1
  4. apiregistration.k8s.io/v1
  5. apps/v1
  6. authentication.k8s.io/v1
  7. authorization.k8s.io/v1
  8. autoscaling/v1
  9. autoscaling/v2beta1
  10. autoscaling/v2beta2
  11. batch/v1
  12. batch/v1beta1
  13. certificates.k8s.io/v1
  14. coordination.k8s.io/v1
  15. crd.projectcalico.org/v1
  16. discovery.k8s.io/v1
  17. discovery.k8s.io/v1beta1
  18. events.k8s.io/v1
  19. events.k8s.io/v1beta1
  20. flowcontrol.apiserver.k8s.io/v1beta1
  21. networking.k8s.io/v1
  22. node.k8s.io/v1
  23. node.k8s.io/v1beta1
  24. policy/v1
  25. policy/v1beta1
  26. rbac.authorization.k8s.io/v1
  27. scheduling.k8s.io/v1
  28. storage.k8s.io/v1
  29. storage.k8s.io/v1beta1
  30. v1
  31. [root@cka-master ~]#

版本选择,针对Deployment来说

序号 版本 备注
1 extensions/v1beta1 1.6版本之前
2 apps/v1beta1 1.6版本到1.9版本
3 apps/v1 1.9

https://matthewpalmer.net/kubernetes-app-developer/articles/kubernetes-apiversion-definition-guide.html

资源注册

通过kubectl api-resources可以看到已经注册的API资源

  1. [root@cka-master ~]# kubectl api-resources
  2. NAME SHORTNAMES APIVERSION NAMESPACED KIND
  3. bindings v1 true Binding
  4. componentstatuses cs v1 false ComponentStatus
  5. configmaps cm v1 true ConfigMap
  6. endpoints ep v1 true Endpoints
  7. events ev v1 true Event
  8. limitranges limits v1 true LimitRange
  9. namespaces ns v1 false Namespace
  10. nodes no v1 false Node
  11. persistentvolumeclaims pvc v1 true PersistentVolumeClaim
  12. persistentvolumes pv v1 false PersistentVolume
  13. pods po v1 true Pod
  14. podtemplates v1 true PodTemplate
  15. replicationcontrollers rc v1 true ReplicationController
  16. resourcequotas quota v1 true ResourceQuota
  17. secrets v1 true Secret
  18. serviceaccounts sa v1 true ServiceAccount
  19. services svc v1 true Service
  20. mutatingwebhookconfigurations admissionregistration.k8s.io/v1 false MutatingWebhookConfiguration
  21. validatingwebhookconfigurations admissionregistration.k8s.io/v1 false ValidatingWebhookConfiguration
  22. customresourcedefinitions crd,crds apiextensions.k8s.io/v1 false CustomResourceDefinition
  23. apiservices apiregistration.k8s.io/v1 false APIService
  24. controllerrevisions apps/v1 true ControllerRevision
  25. daemonsets ds apps/v1 true DaemonSet
  26. deployments deploy apps/v1 true Deployment
  27. replicasets rs apps/v1 true ReplicaSet
  28. statefulsets sts apps/v1 true StatefulSet
  29. tokenreviews authentication.k8s.io/v1 false TokenReview
  30. localsubjectaccessreviews authorization.k8s.io/v1 true LocalSubjectAccessReview
  31. selfsubjectaccessreviews authorization.k8s.io/v1 false SelfSubjectAccessReview
  32. selfsubjectrulesreviews authorization.k8s.io/v1 false SelfSubjectRulesReview
  33. subjectaccessreviews authorization.k8s.io/v1 false SubjectAccessReview
  34. horizontalpodautoscalers hpa autoscaling/v1 true HorizontalPodAutoscaler
  35. cronjobs cj batch/v1 true CronJob
  36. jobs batch/v1 true Job
  37. certificatesigningrequests csr certificates.k8s.io/v1 false CertificateSigningRequest
  38. leases coordination.k8s.io/v1 true Lease
  39. bgpconfigurations crd.projectcalico.org/v1 false BGPConfiguration
  40. bgppeers crd.projectcalico.org/v1 false BGPPeer
  41. blockaffinities crd.projectcalico.org/v1 false BlockAffinity
  42. caliconodestatuses crd.projectcalico.org/v1 false CalicoNodeStatus
  43. clusterinformations crd.projectcalico.org/v1 false ClusterInformation
  44. felixconfigurations crd.projectcalico.org/v1 false FelixConfiguration
  45. globalnetworkpolicies crd.projectcalico.org/v1 false GlobalNetworkPolicy
  46. globalnetworksets crd.projectcalico.org/v1 false GlobalNetworkSet
  47. hostendpoints crd.projectcalico.org/v1 false HostEndpoint
  48. ipamblocks crd.projectcalico.org/v1 false IPAMBlock
  49. ipamconfigs crd.projectcalico.org/v1 false IPAMConfig
  50. ipamhandles crd.projectcalico.org/v1 false IPAMHandle
  51. ippools crd.projectcalico.org/v1 false IPPool
  52. ipreservations crd.projectcalico.org/v1 false IPReservation
  53. kubecontrollersconfigurations crd.projectcalico.org/v1 false KubeControllersConfiguration
  54. networkpolicies crd.projectcalico.org/v1 true NetworkPolicy
  55. networksets crd.projectcalico.org/v1 true NetworkSet
  56. endpointslices discovery.k8s.io/v1 true EndpointSlice
  57. events ev events.k8s.io/v1 true Event
  58. flowschemas flowcontrol.apiserver.k8s.io/v1beta1 false FlowSchema
  59. prioritylevelconfigurations flowcontrol.apiserver.k8s.io/v1beta1 false PriorityLevelConfiguration
  60. ingressclasses networking.k8s.io/v1 false IngressClass
  61. ingresses ing networking.k8s.io/v1 true Ingress
  62. networkpolicies netpol networking.k8s.io/v1 true NetworkPolicy
  63. runtimeclasses node.k8s.io/v1 false RuntimeClass
  64. poddisruptionbudgets pdb policy/v1 true PodDisruptionBudget
  65. podsecuritypolicies psp policy/v1beta1 false PodSecurityPolicy
  66. clusterrolebindings rbac.authorization.k8s.io/v1 false ClusterRoleBinding
  67. clusterroles rbac.authorization.k8s.io/v1 false ClusterRole
  68. rolebindings rbac.authorization.k8s.io/v1 true RoleBinding
  69. roles rbac.authorization.k8s.io/v1 true Role
  70. priorityclasses pc scheduling.k8s.io/v1 false PriorityClass
  71. csidrivers storage.k8s.io/v1 false CSIDriver
  72. csinodes storage.k8s.io/v1 false CSINode
  73. csistoragecapacities storage.k8s.io/v1beta1 true CSIStorageCapacity
  74. storageclasses sc storage.k8s.io/v1 false StorageClass
  75. volumeattachments storage.k8s.io/v1 false VolumeAttachment
  76. [root@cka-master ~]#

通过上表可以确定对应资源的apiVersion,例如pod需要使用的版本为v1

清单文件

通过命令kubectl explain po可以看到资源对象的字段定义

  1. [root@cka-master ~]# kubectl explain po
  2. KIND: Pod
  3. VERSION: v1
  4. DESCRIPTION:
  5. Pod is a collection of containers that can run on a host. This resource is
  6. created by clients and scheduled onto hosts.
  7. FIELDS:
  8. apiVersion <string>
  9. APIVersion defines the versioned schema of this representation of an
  10. object. Servers should convert recognized schemas to the latest internal
  11. value, and may reject unrecognized values. More info:
  12. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
  13. kind <string>
  14. Kind is a string value representing the REST resource this object
  15. represents. Servers may infer this from the endpoint the client submits
  16. requests to. Cannot be updated. In CamelCase. More info:
  17. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
  18. metadata <Object>
  19. Standard object's metadata. More info:
  20. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
  21. spec <Object>
  22. Specification of the desired behavior of the pod. More info:
  23. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
  24. status <Object>
  25. Most recently observed status of the pod. This data may not be up to date.
  26. Populated by the system. Read-only. More info:
  27. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
  28. [root@cka-master ~]#

支持级联操作进行细化

  1. [root@cka-master ~]# kubectl explain po.kind
  2. KIND: Pod
  3. VERSION: v1
  4. FIELD: kind <string>
  5. DESCRIPTION:
  6. Kind is a string value representing the REST resource this object
  7. represents. Servers may infer this from the endpoint the client submits
  8. requests to. Cannot be updated. In CamelCase. More info:
  9. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
  10. [root@cka-master ~]#

结构查看

  1. root@cka-master ~]# kubectl explain po.metadata --recursive
  2. KIND: Pod
  3. VERSION: v1
  4. RESOURCE: metadata <Object>
  5. DESCRIPTION:
  6. Standard object's metadata. More info:
  7. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
  8. ObjectMeta is metadata that all persisted resources must have, which
  9. includes all objects users must create.
  10. FIELDS:
  11. annotations <map[string]string>
  12. clusterName <string>
  13. creationTimestamp <string>
  14. deletionGracePeriodSeconds <integer>
  15. deletionTimestamp <string>
  16. finalizers <[]string>
  17. generateName <string>
  18. generation <integer>
  19. labels <map[string]string>
  20. managedFields <[]Object>
  21. apiVersion <string>
  22. fieldsType <string>
  23. fieldsV1 <map[string]>
  24. manager <string>
  25. operation <string>
  26. subresource <string>
  27. time <string>
  28. name <string>
  29. namespace <string>
  30. ownerReferences <[]Object>
  31. apiVersion <string>
  32. blockOwnerDeletion <boolean>
  33. controller <boolean>
  34. kind <string>
  35. name <string>
  36. uid <string>
  37. resourceVersion <string>
  38. selfLink <string>
  39. uid <string>
  40. [root@cka-master ~]#

命令生成

使用—dry-run参数

  1. [root@cka-master ~]# kubectl run myapp --image=nginx --dry-run -o yaml
  2. W0314 04:53:19.769459 32394 helpers.go:555] --dry-run is deprecated and can be replaced with --dry-run=client.
  3. apiVersion: v1
  4. kind: Pod
  5. metadata:
  6. creationTimestamp: null
  7. labels:
  8. run: myapp
  9. name: myapp
  10. spec:
  11. containers:
  12. - image: nginx
  13. name: myapp
  14. resources: {}
  15. dnsPolicy: ClusterFirst
  16. restartPolicy: Always
  17. status: {}

针对已经存在的资源对象,通过-o参数进行导出

  1. [root@cka-master ~]# kubectl get pod myapp -o yaml
  2. apiVersion: v1
  3. kind: Pod
  4. metadata:
  5. annotations:
  6. cni.projectcalico.org/containerID: 873146677bbf4fa3e23c5fc8803acbe053144c0ab10465262d842df0d9950827
  7. cni.projectcalico.org/podIP: 10.244.115.65/32
  8. cni.projectcalico.org/podIPs: 10.244.115.65/32
  9. creationTimestamp: "2022-03-13T20:54:38Z"
  10. labels:
  11. run: myapp
  12. name: myapp
  13. namespace: default
  14. resourceVersion: "28262"
  15. uid: 905504ca-d4ad-48b0-89b5-2dc1b873ae21
  16. spec:
  17. containers:
  18. - image: nginx
  19. imagePullPolicy: Always
  20. name: myapp
  21. resources: {}
  22. terminationMessagePath: /dev/termination-log
  23. terminationMessagePolicy: File
  24. volumeMounts:
  25. - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
  26. name: kube-api-access-tcmzk
  27. readOnly: true
  28. dnsPolicy: ClusterFirst
  29. enableServiceLinks: true
  30. nodeName: cka-node1
  31. preemptionPolicy: PreemptLowerPriority
  32. priority: 0
  33. restartPolicy: Always
  34. schedulerName: default-scheduler
  35. securityContext: {}
  36. serviceAccount: default
  37. serviceAccountName: default
  38. terminationGracePeriodSeconds: 30
  39. tolerations:
  40. - effect: NoExecute
  41. key: node.kubernetes.io/not-ready
  42. operator: Exists
  43. tolerationSeconds: 300
  44. - effect: NoExecute
  45. key: node.kubernetes.io/unreachable
  46. operator: Exists
  47. tolerationSeconds: 300
  48. volumes:
  49. - name: kube-api-access-tcmzk
  50. projected:
  51. defaultMode: 420
  52. sources:
  53. - serviceAccountToken:
  54. expirationSeconds: 3607
  55. path: token
  56. - configMap:
  57. items:
  58. - key: ca.crt
  59. path: ca.crt
  60. name: kube-root-ca.crt
  61. - downwardAPI:
  62. items:
  63. - fieldRef:
  64. apiVersion: v1
  65. fieldPath: metadata.namespace
  66. path: namespace
  67. status:
  68. conditions:
  69. - lastProbeTime: null
  70. lastTransitionTime: "2022-03-13T20:54:26Z"
  71. status: "True"
  72. type: Initialized
  73. - lastProbeTime: null
  74. lastTransitionTime: "2022-03-13T20:55:01Z"
  75. status: "True"
  76. type: Ready
  77. - lastProbeTime: null
  78. lastTransitionTime: "2022-03-13T20:55:01Z"
  79. status: "True"
  80. type: ContainersReady
  81. - lastProbeTime: null
  82. lastTransitionTime: "2022-03-13T20:54:38Z"
  83. status: "True"
  84. type: PodScheduled
  85. containerStatuses:
  86. - containerID: docker://f83bef188bee675668dd87ed0661512037fd8a623a11f2fdc33671c62823fc5e
  87. image: nginx:latest
  88. imageID: docker-pullable://nginx@sha256:0d17b565c37bcbd895e9d92315a05c1c3c9a29f762b011a10c54a66cd53c9b31
  89. lastState: {}
  90. name: myapp
  91. ready: true
  92. restartCount: 0
  93. started: true
  94. state:
  95. running:
  96. startedAt: "2022-03-13T20:55:00Z"
  97. hostIP: 192.168.184.129
  98. phase: Running
  99. podIP: 10.244.115.65
  100. podIPs:
  101. - ip: 10.244.115.65
  102. qosClass: BestEffort
  103. startTime: "2022-03-13T20:54:26Z"
  104. [root@cka-master ~]#