K8s Crd From Typed Schemaのロゴ

K8s Crd From Typed Schema

コミュニティ
mizchi
k8s-crd-from-typed-schema

型付きスキーマソース(zod / TypeBox / Valibot / json-schema)からKubernetes CustomResourceDefinitionsを生成するときに使います。Structural Schema方言の制約、/statusサブリソースの落とし穴、metadata禁止ルール、複数形への変換という、初回に陥りやすい4つの問題を扱います。

Add to TypingMind

概要

公開者mizchi
リポジトリskills
スキル名k8s-crd-from-typed-schema
スター
333
フォーク
4
同梱ファイル
指示のみ
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 指示だけで完結

    モデルに必要なものはすべて指示に含まれているため、別途同期するファイルはありません。

  • オープンソース

    mizchiがGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキル「K8s Crd From Typed Schema」をTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/mizchi/skills/tree/main/k8s-crd-from-typed-schema
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/mizchi/skills.git /tmp/skills
mkdir -p .claude/skills
cp -r /tmp/skills/k8s-crd-from-typed-schema .claude/skills/k8s-crd-from-typed-schema
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでK8s Crd From Typed Schemaを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあるとすぐに、モデルが自動的にK8s Crd From Typed Schemaを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、K8s Crd From Typed Schemaは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、スキルを使わない間は指示の読み込みにトークンを消費しません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

k8s CRDs from a typed schema

Generating CRDs from typed schemas (zod / TypeBox / Valibot / hand-written JSON Schema) looks straightforward — convert to OpenAPI v3, embed as openAPIV3Schema, done. It isn't. CRDs use a subset of OpenAPI v3 plus k8s-specific extensions ("Structural Schema"), and several common JSON-Schema features are silently incompatible. Plus there are two non-schema gotchas (status subresource, metadata prohibition) that don't show up until you try to use the CRD.

This skill is the punch list of what to fix before kubectl apply -f crd.yaml succeeds and the operator actually works.

When to use

  • Building an operator / controller and writing your own CRDs.
  • Generating CRDs from a typed source rather than hand-authoring YAML.
  • Hitting kubectl errors like unknown field "$schema" / must not have "oneOf" / must not specify anything other than name and generateName / cannot have both "additionalProperties" and "properties".
  • Operator works once but then reconciles forever in a loop after the first status write.

Workflow

1. Convert typed schema → JSON Schema (OpenAPI v3 dialect)

For zod:

ts
import { zodToJsonSchema } from 'zod-to-json-schema';

const json = zodToJsonSchema(specSchema, {
  target: 'openApi3',
  $refStrategy: 'none',  // CRDs forbid $refs across the document
});

$refStrategy: 'none' is mandatory — k8s' Structural Schema does not resolve cross-document $ref. Inline everything.

For TypeBox: pass the schema through as-is, then run the adapter below.

2. Run the Structural-Schema adapter

The Structural Schema dialect rejects several JSON Schema features. Strip / rewrite them:

JSON Schema featureWhat to doWhy
$schema meta keyworddropkubectl rejects unknown root keys
oneOf / anyOf / allOfreplace the node with { x-kubernetes-preserve-unknown-fields: true }structural schema forbids schema-form unions outside x-kubernetes-validations
tuple items (array of schemas)collapse to a single schema (use items[0])k8s only supports a single item schema
format other than uri / date-timedrop the format keyapiserver only honors a small whitelist; unknown formats fail validation
additionalProperties: false co-located with propertiesdrop the additionalProperties keystructural schema forbids both at once; declared properties already implies closed
empty leaf {} (e.g. from z.unknown())replace with { x-kubernetes-preserve-unknown-fields: true }structural schema requires every node to declare a type or use the escape hatch

A reference adapter (TypeScript, ~40 lines) lives at examples/adapter.ts in this skill (or copy from k1c/src/cli/export-crds.ts).

3. Wrap the spec schema in the CRD envelope

yaml
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: <plural>.<group>     # e.g. r2buckets.cloudflare.k1c.io
spec:
  group: <group>
  scope: Namespaced
  names:
    kind: <Kind>
    singular: <kind>
    plural: <plural>
    listKind: <Kind>List
  versions:
    - name: v1alpha1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          properties:
            apiVersion: { type: string }
            kind:       { type: string }
            spec:       <your adapted schema here>
            status:
              type: object
              x-kubernetes-preserve-unknown-fields: true
          required: [spec]
      subresources:
        status: {}            # <-- mandatory if your operator writes status

4. Compute the plural correctly

spec.names.plural ends up in the kubectl URL (/apis/<group>/<version>/<plural>). Don't kind.toLowerCase() + 's' — handle the regular-verb cases:

ts
function pluralize(kind: string): string {
  const lower = kind.toLowerCase();
  if (lower.endsWith('s') || lower.endsWith('x') || lower.endsWith('z')) return `${lower}es`;
  if (lower.endsWith('y')) return `${lower.slice(0, -1)}ies`;
  return `${lower}s`;
}

This matches the inflection Cloudflare and most k8s API authors use. Irregular kinds (Endpoints, Quota → quotas) need a manual override map.

5. Verify with kubectl in dry-run mode

sh
kubectl apply --dry-run=server -f crd.yaml
kubectl apply --dry-run=server -f sample-cr.yaml   # after CRD is registered

Server-side dry-run catches structural-schema violations that local dry-run misses (e.g. additionalProperties + properties is only enforced server-side).

Pitfalls

Pitfall 1: declaring metadata in openAPIV3Schema.properties

yaml
# ❌ kubectl rejects this:
openAPIV3Schema:
  type: object
  properties:
    metadata: { type: object, properties: { name: { type: string } } }
    spec: ...
# error: must not specify anything other than name and generateName for metadata

Fix: don't list metadata at all. The apiserver auto-applies the standard ObjectMeta schema. Only declare apiVersion / kind / spec / status.

Pitfall 2: missing subresources.status: {} causes infinite reconcile loops

Without this, every kubectl patch --subresource=status call:

  1. Bumps .metadata.generation.
  2. Wakes up the watch.
  3. Operator re-reconciles → patches status again.
  4. Goto 1.

Symptom: operator looks healthy but logs show reconcile loop lines firing every few hundred ms forever. CPU climbs slowly. Apiserver QPS budget burns.

Fix: always include subresources: { status: {} } in every served version.

Pitfall 3: oneOf from discriminated unions

z.discriminatedUnion(...) and Type.Union(...) lower to oneOf. Structural schema rejects this outside x-kubernetes-validations (CEL). Two fixes:

  1. Permissive escape: replace the node with x-kubernetes-preserve-unknown-fields: true (loses validation).
  2. Strict CEL: emit x-kubernetes-validations: [{ rule: "self.type == 'a' && has(self.payload)" }]. Only apiserver ≥ 1.25 supports this.

The adapter in step 2 picks option 1 by default. Bump to option 2 only when the validation is load-bearing.

Pitfall 4: structural schema requires type on every node

z.unknown() lowers to an empty {} JSON Schema. Structural schema rejects nodes without type (or enum, or the escape hatch). Stamp x-kubernetes-preserve-unknown-fields: true on every empty leaf during adaptation.

Pitfall 5: only one schema can be the storage version

versions[N].storage: true must be exactly one entry per CRD across all served versions. Multiple storage: true → apiserver refuses the CRD on registration. When adding v1beta1 → v1, flip exactly one over.

Verifying without a real cluster

Stand up kind in CI and run:

sh
kubectl apply -f crd.yaml                              # registers the CRD
kubectl apply --dry-run=server -f every-example.yaml   # validates each CR against the new schema

This is exactly what k1c does in .github/workflows/k8s-validate.yml — see that workflow for a reference job.

Why this matters

CRDs are a contract between humans, the apiserver, and your operator. The Structural Schema rules are not arbitrary — they exist so the apiserver can do server-side validation, defaulting, and pruning. But the rules aren't documented in one place: the official Structural Schema docs cover the dialect, the subresource docs cover /status, and the metadata prohibition only shows up as a runtime apiserver error. This skill collapses all four into one workflow.

Related skills

  • cloudflare-deploy — for Cloudflare-specific resource shapes if you're operating on CF (independent of CRD generation).
  • apm-usage — for shipping the generated CRD bundle as a skill artifact.

よくある質問

AIスキル「K8s Crd From Typed Schema」では何ができますか?

型付きスキーマソース(zod / TypeBox / Valibot / json-schema)からKubernetes CustomResourceDefinitionsを生成するときに使います。Structural Schema方言の制約、/statusサブリソースの落とし穴、metadata禁止ルール、複数形への変換という、初回に陥りやすい4つの問題を扱います。

TypingMindでK8s Crd From Typed Schemaを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。K8s Crd From Typed Schemaはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにK8s Crd From Typed Schemaをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/mizchi/skills/tree/main/k8s-crd-from-typed-schemaを貼り付けてください。TypingMindがSKILL.mdを読み込み、チャットごとに有効にできるスキルとしてインストールします。

K8s Crd From Typed Schemaを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストの内容がこのスキルの用途に合ったときに、このスキルを読み込めます。

K8s Crd From Typed Schemaで使えるAIモデルの数に制限はありますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもK8s Crd From Typed Schemaを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「K8s Crd From Typed Schema」は無料ですか?

mizchiがGitHubで公開しています。ライセンス条件はリポジトリでご確認ください。ご利用のAIプロバイダーに支払うのは、使用したトークンの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇