kubernetes學習記錄(14)——使用CustomResourceDefinitions(CRD)擴展Kubernetes API

工作中即將開始寫operator,先提前學習一下相關的知識

目前我們的kubernetes集羣版本爲1.15.0,故參考文檔爲官方文檔《Extend the Kubernetes API with CustomResourceDefinitions》

創建一個CustomResourceDefinition

  • 官方例子
# resourcedefinition.yaml
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  # name must match the spec fields below, and be in the form: <plural>.<group>
  name: crontabs.stable.example.com
spec:
  # group name to use for REST API: /apis/<group>/<version>
  group: stable.example.com
  # list of versions supported by this CustomResourceDefinition
  versions:
    - name: v1
      # Each version can be enabled/disabled by Served flag.
      served: true
      # One and only one version must be marked as the storage version.
      storage: true
  # either Namespaced or Cluster
  scope: Namespaced
  names:
    # plural name to be used in the URL: /apis/<group>/<version>/<plural>
    plural: crontabs
    # singular name to be used as an alias on the CLI and for display
    singular: crontab
    # kind is normally the CamelCased singular type. Your resource manifests use this.
    kind: CronTab
    # shortNames allow shorter string to match your resource on the CLI
    shortNames:
    - ct
  preserveUnknownFields: false
  validation:
    openAPIV3Schema:
      type: object
      properties:
        spec:
          type: object
          properties:
            cronSpec:
              type: string
            image:
              type: string
            replicas:
              type: integer
  • 根據yaml創建crd
# kubectl apply -f resourcedefinition.yaml
customresourcedefinition.apiextensions.k8s.io/crontabs.stable.example.com created
# kubectl get crd | grep crontabs
crontabs.stable.example.com             2020-01-08T07:49:53Z

創建自定義對象

  • 根據上文定義的CRD,創建CRD對象
# my-crontab.yaml
apiVersion: "stable.example.com/v1"
kind: CronTab
metadata:
  name: my-new-cron-object
spec:
  cronSpec: "* * * * */5"
  image: my-awesome-cron-image
# kubectl apply -f my-crontab.yaml
# kubectl get crontab
NAME                 AGE
my-new-cron-object   28s

刪除自定義對象

刪除CustomResourceDefinition時,服務器將卸載RESTful API端點並刪除其中存儲的所有自定義對象

# kubectl delete -f resourcedefinition.yaml
# kubectl get crontabs
Error from server (NotFound): Unable to list "stable.example.com/v1, Resource=crontabs": the server could not find the requested resource (get crontabs.stable.example.com)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章