kubertes② 〜CRを作ってみる〜

CR (Custom Resource)

KubernetesAPIのエンドポイントで特定のAPIオブジェクトのコレクションを保持するもの。
デフォルトではpodとかdeploymentとかあるが、これを自分でも作れちゃうということ。
実態としてはユーザが定義したデータ構造およびそれの入出力を提供する機能とのこと。

CRD (Custom Resource Definition)

CRの定義。

exampleのCRを作ってみる。

まずはCRDのマニフェストファイル。

apiVersion: apiextensions.k8s.io/v1
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
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                cronSpec:
                  type: string
                image:
                  type: string
                replicas:
                  type: integer
  # 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

CRDを作成してみる。

$ kubectl apply -f resourcedefinition.yaml 
customresourcedefinition.apiextensions.k8s.io/crontabs.stable.example.com created

CRDとして登録されている。

$ kubectl get crd
NAME                          CREATED AT
crontabs.stable.example.com   2021-12-21T14:12:36Z

作成したcrontabリソースのためのAPIもちゃんと生えている

$ kubectl get crontabs.stable.example.com
No resources found in default namespace.
$ kubectl get crontab
No resources found in default namespace.
$ kubectl get ct
No resources found in default namespace.

CRのマニフェストは以下になる。

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
crontab.stable.example.com/my-new-cron-object created
$
$ kubectl get ct
NAME                 AGE
my-new-cron-object   51s

参考

  1. https://kubernetes.io/ja/docs/concepts/extend-kubernetes/api-extension/custom-resources/
  2. https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#specifying-a-structural-schema