Token导航 LogoToken导航TokenDH.com
运维和基础设施需要联网github未标认证来源可访问clear审计通过

cel-k8sCEL Kubernetes 命令行

Agent Skill

cel-k8s 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

269

周安装

11

GitHub Stars

40

下载量

86
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:cel-k8s(CEL Kubernetes 命令行)
来源仓库:https://github.com/tyrchen/claude-skills
仓库路径:skills/cel-k8s
安装命令:
npx skills add https://github.com/tyrchen/claude-skills --skill cel-k8s
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/tyrchen/claude-skills --skill cel-k8s

简介

cel-k8s 用于生成生产级 CEL 代码,支持 Kubernetes 准入控制和 CRD 验证。

  • 适合在 Codex、Claude、Cursor、Gemini CLI 中需要编写 ValidatingAdmissionPolicy 或安全策略时使用。
  • 可创建 x-kubernetes-validations 规则,无需外部 webhook 即可实现细粒度校验。
  • 安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。
  • cel-k8s 属于运维和基础设施类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

CEL for Kubernetes - Production-Ready Policy Generator

Generate solid, high-quality, production-ready CEL (Common Expression Language) code for Kubernetes admission control, CRD validation, and security policy enforcement.

When to Use This Skill

Use this skill when the user wants to:

  • Write ValidatingAdmissionPolicy resources with CEL expressions
  • Create CRD validation rules using x-kubernetes-validations
  • Enforce security policies (Pod Security Standards, image restrictions, etc.)
  • Validate resource configurations (labels, annotations, resource limits)
  • Build admission control without external webhooks
  • Migrate from OPA/Gatekeeper/Kyverno to native Kubernetes CEL
  • Debug or optimize existing CEL expressions

CEL Quick Reference

Core Operators

// Comparison
==  !=  <  <=  >  >=

// Logical
&&  ||  !

// Arithmetic
+  -  *  /  %

// Membership
in  // Check if element exists in collection

// Ternary
condition ? trueValue : falseValue

Essential Functions

// Field existence (CRITICAL - always check before accessing optional fields)
has(object.spec.field)

// String functions
size(string)                    // Length
contains(string, substring)     // Contains check
startsWith(string, prefix)      // Prefix check
endsWith(string, suffix)        // Suffix check
matches(string, regex)          // Regex match
split(string, delimiter)        // Split to list
lower(string)                   // Lowercase
upper(string)                   // Uppercase
trim(string)                    // Remove whitespace

// Collection functions
size(list)                      // List length
all(list, var, condition)       // All elements satisfy
exists(list, var, condition)    // Any element satisfies
exists_one(list, var, condition) // Exactly one satisfies
filter(list, var, condition)    // Filter elements
map(list, var, transformation)  // Transform elements

// Kubernetes-specific
quantity(string)                // Parse K8s quantity (e.g., "2Gi", "500m")
isQuantity(string)              // Validate quantity format
url(string)                     // Parse URL

Available Context Variables

In ValidatingAdmissionPolicy:

  • object - The incoming resource being validated
  • oldObject - The existing resource (UPDATE operations)
  • request - Admission request metadata (user, operation, namespace)
  • params - Parameters from ValidatingAdmissionPolicyBinding
  • namespaceObject - The namespace resource

In CRD Validation (x-kubernetes-validations):

  • self - The field being validated
  • oldSelf - Previous field value (UPDATE)

Instructions for Writing CEL Policies

Step 1: Understand the Requirement

Before writing any CEL:

  1. What resource types need validation? (Deployments, Pods, Services, etc.)
  2. What operations should trigger validation? (CREATE, UPDATE, DELETE)
  3. What specific conditions must be enforced?
  4. Should violations block the request or just audit?

Step 2: Design the Expression

Follow these principles:

1. Always use has() for optional fields:

// CORRECT - Safe field access
has(object.spec.template.spec.securityContext) &&
object.spec.template.spec.securityContext.runAsNonRoot == true

// WRONG - Will error if field doesn't exist
object.spec.template.spec.securityContext.runAsNonRoot == true

2. Handle null/missing values gracefully:

// Check for labels existence before accessing
has(object.metadata.labels) &&
'app' in object.metadata.labels &&
object.metadata.labels['app'] == 'myapp'

3. Use short-circuit evaluation:

// Fast checks first, expensive operations last
has(object.metadata.labels) &&           // Fast: field existence
'app' in object.metadata.labels &&       // Medium: map lookup
object.metadata.labels['app'].matches('^[a-z]+$')  // Slow: regex

4. Prefer positive assertions:

// BETTER - Clear intent
object.spec.replicas >= 1 && object.spec.replicas <= 10

// AVOID - Double negatives
!(object.spec.replicas < 1 || object.spec.replicas > 10)

Step 3: Write the ValidatingAdmissionPolicy

Use this structure:

apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
  name: "policy-name.example.com"
spec:
  failurePolicy: Fail  # or Ignore for non-critical policies
  matchConstraints:
    resourceRules:
    - apiGroups: ["apps"]
      apiVersions: ["v1"]
      operations: ["CREATE", "UPDATE"]
      resources: ["deployments"]
  validations:
  - expression: "CEL expression here"
    message: "Human-readable error message"
    messageExpression: "'Dynamic message with ' + object.metadata.name"

Step 4: Create the Binding

apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
  name: "policy-binding"
spec:
  policyName: "policy-name.example.com"
  validationActions: [Deny]  # or [Audit] for testing
  matchResources:
    namespaceSelector:
      matchLabels:
        environment: production

Step 5: Test Before Deploying

  1. Use dry-run mode: kubectl apply --dry-run=server -f test-resource.yaml
  2. Start with Audit mode: validationActions: [Audit] # Log violations, don't block
  3. Check events for violations: kubectl get events --field-selector reason=PolicyAudit

Common Policy Patterns

Security Policies

Require non-root containers:

validations:
- expression: |
    has(object.spec.template.spec.securityContext) &&
    has(object.spec.template.spec.securityContext.runAsNonRoot) &&
    object.spec.template.spec.securityContext.runAsNonRoot == true
  message: "Pods must run as non-root user"

Disallow privileged containers:

validations:
- expression: |
    !has(object.spec.template.spec.containers) ||
    !object.spec.template.spec.containers.exists(c,
      has(c.securityContext) &&
      has(c.securityContext.privileged) &&
      c.securityContext.privileged == true
    )
  message: "Privileged containers are not allowed"

Drop all capabilities:

validations:
- expression: |
    object.spec.template.spec.containers.all(c,
      has(c.securityContext) &&
      has(c.securityContext.capabilities) &&
      has(c.securityContext.capabilities.drop) &&
      c.securityContext.capabilities.drop.exists(cap, cap == 'ALL')
    )
  message: "All containers must drop ALL capabilities"

Restrict to approved registries:

validations:
- expression: |
    object.spec.template.spec.containers.all(c,
      c.image.startsWith('myregistry.io/') ||
      c.image.startsWith('gcr.io/myproject/')
    )
  message: "Container images must come from approved registries"

Disallow latest tag:

validations:
- expression: |
    object.spec.template.spec.containers.all(c,
      c.image.contains(':') && !c.image.endsWith(':latest')
    )
  message: "Container images must not use 'latest' tag"

Resource Validation

Require resource limits:

validations:
- expression: |
    object.spec.template.spec.containers.all(c,
      has(c.resources) &&
      has(c.resources.limits) &&
      has(c.resources.limits.memory) &&
      has(c.resources.limits.cpu) &&
      has(c.resources.requests) &&
      has(c.resources.requests.memory) &&
      has(c.resources.requests.cpu)
    )
  message: "All containers must define CPU and memory limits and requests"

Enforce resource quotas:

validations:
- expression: |
    object.spec.template.spec.containers.all(c,
      !has(c.resources.requests.memory) ||
      quantity(c.resources.requests.memory) <= quantity('2Gi')
    )
  message: "Memory requests cannot exceed 2Gi per container"

Label and Annotation Validation

Require specific labels:

validations:
- expression: |
    has(object.metadata.labels) &&
    'app' in object.metadata.labels &&
    'environment' in object.metadata.labels &&
    'team' in object.metadata.labels
  message: "Resources must have 'app', 'environment', and 'team' labels"

Validate label values:

validations:
- expression: |
    !has(object.metadata.labels) ||
    !('environment' in object.metadata.labels) ||
    object.metadata.labels['environment'] in ['dev', 'staging', 'prod']
  message: "environment label must be one of: dev, staging, prod"

Validate naming conventions:

validations:
- expression: |
    object.metadata.name.matches('^[a-z][a-z0-9-]*[a-z0-9]$') &&
    object.metadata.name.size() <= 63
  message: "Resource name must be lowercase alphanumeric with hyphens, max 63 chars"

Network Policies

Disallow hostNetwork:

validations:
- expression: |
    !has(object.spec.template.spec.hostNetwork) ||
    object.spec.template.spec.hostNetwork == false
  message: "hostNetwork is not allowed"

Disallow hostPath volumes:

validations:
- expression: |
    !has(object.spec.template.spec.volumes) ||
    object.spec.template.spec.volumes.all(v, !has(v.hostPath))
  message: "hostPath volumes are not allowed"

CRD Validation Rules

For CustomResourceDefinitions, use x-kubernetes-validations:

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: myresources.example.com
spec:
  group: example.com
  versions:
  - name: v1
    schema:
      openAPIV3Schema:
        type: object
        properties:
          spec:
            type: object
            properties:
              replicas:
                type: integer
                minimum: 1
                maximum: 100
                x-kubernetes-validations:
                - rule: "self >= 1 && self <= 100"
                  message: "Replicas must be between 1 and 100"
              schedule:
                type: string
                x-kubernetes-validations:
                - rule: "self.matches('^(\\\\d+|\\\\*)(/\\\\d+)?(\\\\s+(\\\\d+|\\\\*)(/\\\\d+)?){4}$')"
                  message: "Must be a valid cron expression"
            x-kubernetes-validations:
            - rule: "has(self.replicas) || has(self.schedule)"
              message: "Either replicas or schedule must be specified"

Performance Best Practices

Set Schema Constraints

Help the cost estimator by bounding collections:

properties:
  containers:
    type: array
    maxItems: 20       # Bound array iterations
  labels:
    type: object
    maxProperties: 50  # Bound map operations
  name:
    type: string
    maxLength: 253     # Bound string operations

Avoid O(n^2) Patterns

# BAD - O(n^2): Nested iteration over same collection
- expression: |
    object.spec.containers.all(c1,
      object.spec.containers.all(c2,
        c1.name != c2.name || c1 == c2
      )
    )

# GOOD - O(n): Use unique check
- expression: |
    object.spec.containers.map(c, c.name).size() ==
    object.spec.containers.size()
  message: "Container names must be unique"

Use Targeted Match Rules

Limit policy scope to reduce evaluations:

matchConstraints:
  resourceRules:
  - apiGroups: ["apps"]          # Specific group
    apiVersions: ["v1"]           # Specific version
    operations: ["CREATE"]        # Only CREATE, not every operation
    resources: ["deployments"]    # Specific resource
  namespaceSelector:              # Target specific namespaces
    matchLabels:
      enforce-policies: "true"

Debugging CEL Expressions

Common Errors and Fixes

Error: "no such key"

// Problem: Accessing map key that doesn't exist
object.metadata.labels['app']

// Fix: Check key existence
has(object.metadata.labels) && 'app' in object.metadata.labels &&
object.metadata.labels['app']

Error: "type mismatch"

// Problem: Comparing wrong types
object.spec.replicas == "5"

// Fix: Use correct type
object.spec.replicas == 5

Error: "no such field"

// Problem: Accessing field on null object
object.spec.securityContext.runAsNonRoot

// Fix: Check parent existence
has(object.spec.securityContext) &&
object.spec.securityContext.runAsNonRoot == true

Testing Commands

# Test with dry-run
kubectl apply --dry-run=server -f resource.yaml

# Check policy status
kubectl get validatingadmissionpolicy
kubectl describe validatingadmissionpolicy <name>

# View audit events
kubectl get events --field-selector reason=PolicyAudit

# Check type checking warnings
kubectl get validatingadmissionpolicy <name> -o yaml | grep -A 20 typeChecking

Output Format

When generating CEL policies, always provide:

  1. Complete ValidatingAdmissionPolicy YAML
  2. Corresponding ValidatingAdmissionPolicyBinding YAML
  3. Test resources (both passing and failing examples)
  4. Explanation of each validation rule
  5. Deployment instructions

Reference Files

Kubernetes Version Compatibility

  • CEL in ValidatingAdmissionPolicy: GA in Kubernetes 1.30+
  • CEL in CRD validation: GA in Kubernetes 1.29+
  • Alpha/Beta: Available in earlier versions with feature gates

Always verify target cluster version before generating policies.

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude Code

28.58%
按下载量换算25

OpenCode

23.08%
按下载量换算20

windsurf

16.57%
按下载量换算14

Antigravity

11.9%
按下载量换算10

Codex

6.54%
按下载量换算6

Gemini CLI

2.79%
按下载量换算2

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

来源信息

继续浏览同类 Skills