k8s-crd-design
CRD schema, webhook, RBAC, and reconcile loop patterns
Works with
---
name: k8s-crd-design
description: CRD schema, webhook, RBAC, and reconcile loop patterns
license: MIT
---
# Kubernetes CRD Design Patterns
Use these patterns when designing and implementing CRDs, webhooks, controllers, and RBAC for Kubernetes operators.
## 1. Problem Framing
Before writing code, answer:
- Summarize the user problem in one sentence.
- List the CRD's top 3 responsibilities.
- Identify safety risks (what could go wrong if the controller misbehaves?).
## 2. CRD Schema Design
Propose a CRD with:
- **Spec fields**: Required fields with types and validation markers. Use kubebuilder markers (`+kubebuilder:validation:*`).
- **Status fields**: Observed state, conditions, and last-reconciled generation.
- **Defaults**: Use `+kubebuilder:default:=` markers for sensible defaults.
- **Validation**: Use `+kubebuilder:validation:Enum`, `+kubebuilder:validation:Minimum`, `+kubebuilder:validation:Pattern` as appropriate.
- **Printer columns**: Add `+kubebuilder:printcolumn` for useful `kubectl get` output.
Example pattern:
```go
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:printcolumn:name="Ready",type=string,JSONPath=`.status.conditions[?(@.type=="Ready")].status`
// +kubebuilder:printcolumn:name="Age",type=date,JSONPath=`.metadata.creationTimestamp`
type MyResource struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec MyResourceSpec `json:"spec,omitempty"`
Status MyResourceStatus `json:"status,omitempty"`
}
```
## 3. Webhook Design
### Validating Webhook
- Block invalid creates and updates.
- Enforce immutable fields on update.
- Validate cross-field constraints.
- Return clear error messages.
### Mutating Webhook
- Only default safe, optional fields.
- Never mutate fields the user explicitly set.
- Add labels/annotations the controller needs.
- Keep mutations minimal and predictable.
### Failure Policy
- **Dev**: `Ignore` (don't block the cluster if webhook is down)
- **Production**: `Fail` (safety over availability)
## 4. Reconcile Loop Outline
Standard reconcile pattern:
1. Fetch the CR by name. If not found, return (deleted).
2. Check for deletion timestamp — handle finalizers.
3. Compute desired state from spec.
4. For each owned resource:
- Get current state
- Compare with desired state
- Create, update, or delete as needed
5. Update CR status with observed state and conditions.
6. Requeue if needed (e.g., waiting for external resource).
Key principles:
- **Idempotent**: Safe to call multiple times with the same input.
- **Level-triggered**: React to current state, not events.
- **Owner references**: Set on all created resources for garbage collection.
- **Status conditions**: Use standard condition types (Ready, Progressing, Degraded).
## 5. RBAC Minimization
List the minimal permissions the controller needs:
- **Own CRD**: get, list, watch, update (status subresource), patch
- **Owned resources**: get, list, watch, create, update, patch, delete
- **Events**: create, patch (for recording events)
- **Webhook**: no extra RBAC (handled by API server)
Avoid:
- Cluster-wide permissions unless the CRD is cluster-scoped
- Wildcard resources or verbs
- Permissions on resources the controller doesn't manage
## 6. Test Outline
Minimum test coverage:
- **Unit tests**: Reconcile logic with mock client (table-driven)
- **Envtest tests**: Full API server + etcd for webhook validation
- **Example manifests**: Valid and invalid CRs for manual testing
```go
// Example envtest setup
var _ = BeforeSuite(func() {
testEnv = &envtest.Environment{
CRDDirectoryPaths: []string{filepath.Join("..", "config", "crd", "bases")},
WebhookInstallOptions: envtest.WebhookInstallOptions{
Paths: []string{filepath.Join("..", "config", "webhook")},
},
}
// ...
})
```More API Design skills
lark-event
larksuite/cli
Lark/Feishu real-time event listening / subscribing / consuming: stream events as NDJSON via `lark-cli event consume <EventKey>` (covers IM messages/reactions/chat changes, Approval status changes, Task updates, VC meeting started/joined/ended, Minutes generated, Whiteboard updated, etc.). Use for Lark bots, real-time message processing, long-running subscribers, streaming webhook/push handlers. Supports `--max-events` / `--timeout` bounded runs and a stderr ready-marker contract — designed for AI agents running as subprocesses.
lark-contact
larksuite/cli
飞书 / Lark 通讯录:按姓名 / 邮箱解析成 open_id,或按 open_id 反查姓名 / 部门 / 邮箱 / 联系方式 / 个人状态 / 签名,以及按关键词搜索当前用户可见的机器人 / 智能体(agent)。当用户提到一个名字要下一步发消息 / 排日程,或拿到 open_id 想查具体信息时使用。不负责部门树遍历、按部门列员工、组织架构图,这类需求走原生 OpenAPI。
lark-openapi-explorer
larksuite/cli
飞书/Lark 原生 OpenAPI 探索:从官方文档库中挖掘未经 CLI 封装的原生 OpenAPI 接口。当用户的需求无法被现有 lark-* skill 或 lark-cli 已注册命令满足,需要查找并调用原生飞书 OpenAPI 时使用。

