kubertes③ additionalPrinterColumns

additionalPrinterColumnsというものを使うとgetに新しいフィールドを追加できる。

方法

以前の記事で紹介したものを拡張して使う。
kubectlはk8sのマスターノードにあるAPIサーバのクライアント、kubectl get はAPIサーバーから取得したデータをターミナルにアウトプットしてくれている。
CRDにおいてgetに新しいフィールドを追加する場合、additionalPrinterColumnsというフィールドを使って、APIサーバーから返されるJSONの特定のリソースを指定する。

やってみる

まずは既存のものを確認。

$ kubectl get ct
NAME                 AGE
my-new-cron-object   11d

CRDを編集。 編集箇所はadditionalPrinterColumnsフィールドの追加だけ。

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
      additionalPrinterColumns:
        - name: Spec
          type: string
          description: The cron spec defining the interval a CronJob is run
          jsonPath: .spec.cronSpec
        - name: Replicas
          type: integer
          description: The number of jobs launched by the CronJob
          jsonPath: .spec.replicas
        - name: Age
          type: date
          jsonPath: .metadata.creationTimestamp
  # 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

additionalPrinterColumnsのjsonPathで指定する値がサーバー返されるjsonの中の欲しいフィールドを指定している所。
これはkubectl get ct my-new-cron-object -o jsonとかで調べればよいと思う。

CRDをApply。

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

kubectl get で確認。

$ kubectl get ct
NAME                 SPEC          REPLICAS   AGE
my-new-cron-object   * * * * */5              11d

SPECとかREPLICASとか表示されてて、上手くいっているっぽい。

参考

https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#additional-printer-columns