cel-k8s
Write production-ready CEL (Common Expression Language) code for Kubernetes ValidatingAdmissionPolicies, CRD validation rules, and security policies. Use when users need to create admission policies, validate Kubernetes resources, enforce security constraints, or write CEL expressions for Kubernetes.
What this skill does
# 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
```cel
// Comparison
== != < <= > >=
// Logical
&& || !
// Arithmetic
+ - * / %
// Membership
in // Check if element exists in collection
// Ternary
condition ? trueValue : falseValue
```
### Essential Functions
```cel
// 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:**
```cel
// 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:**
```cel
// 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:**
```cel
// 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:**
```cel
// 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:
```yaml
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
```yaml
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:**
```bash
kubectl apply --dry-run=server -f test-resource.yaml
```
2. **Start with Audit mode:**
```yaml
validationActions: [Audit] # Log violations, don't block
```
3. **Check events for violations:**
```bash
kubectl get events --field-selector reason=PolicyAudit
```
## Common Policy Patterns
### Security Policies
**Require non-root containers:**
```yaml
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:**
```yaml
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:**
```yaml
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:**
```yaml
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:**
```yaml
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:**
```yaml
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:**
```yaml
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:**
```yaml
validations:
- expression: |
has(object.metadata.labels) &&
'app' in object.metadata.labels &&
'environment' in object.metadata.labels &&
Related in Cloud & DevOps
appbuilder-action-scaffolder
IncludedCreate, implement, deploy, and debug Adobe Runtime actions with consistent layout, validation, and error handling. Use this skill whenever the user needs to add actions to an App Builder project, understand action structure (params, response format, web/raw actions), configure actions in the manifest, use App Builder SDKs (State, Files, Events, database), deploy and invoke actions via CLI, debug action issues, or implement patterns such as webhook receivers, custom event providers, journaling consumers, large payload redirects, action sequence pipelines, and Asset Compute workers. Also trigger when users mention serverless functions in Adobe context, action logging, IMS authentication for actions, or cron-style scheduled actions.
orchestrating-datacloud
IncludedSalesforce Data Cloud product orchestrator for connect→prepare→harmonize→segment→act workflows. Use this skill when the user needs a multi-step Data Cloud pipeline, cross-phase troubleshooting, or data space and data kit management. TRIGGER when: user needs a multi-step Data Cloud pipeline, asks to set up or troubleshoot Data Cloud across phases, manages data spaces or data kits, or wants a cross-phase sf data360 workflow. DO NOT TRIGGER when: work is isolated to a single phase (use the matching phase-specific skill), the task is STDM/session tracing/parquet telemetry (use observing-agentforce), standard CRM SOQL (use querying-soql), or Apex implementation (use generating-apex).
github-project-automation
IncludedAutomate GitHub repository setup with CI/CD workflows, issue templates, Dependabot, and CodeQL security scanning. Includes 12 production-tested workflows and prevents 18 errors: YAML syntax, action pinning, and configuration. Use when: setting up GitHub Actions CI/CD, creating issue/PR templates, enabling Dependabot or CodeQL scanning, deploying to Cloudflare Workers, implementing matrix testing, or troubleshooting YAML indentation, action version pinning, secrets syntax, runner versions, or CodeQL configuration. Keywords: github actions, github workflow, ci/cd, issue templates, pull request templates, dependabot, codeql, security scanning, yaml syntax, github automation, repository setup, workflow templates, github actions matrix, secrets management, branch protection, codeowners, github projects, continuous integration, continuous deployment, workflow syntax error, action version pinning, runner version, github context, yaml indentation error
sf-datacloud
IncludedSalesforce Data Cloud product orchestrator for connect→prepare→harmonize→segment→act workflows. TRIGGER when: user needs a multi-step Data Cloud pipeline, asks to set up or troubleshoot Data Cloud across phases, manages data spaces or data kits, or wants a cross-phase `sf data360` workflow. DO NOT TRIGGER when: work is isolated to a single phase (use the matching sf-datacloud-* skill), the task is STDM/session tracing/parquet telemetry (use sf-ai-agentforce-observability), standard CRM SOQL (use sf-soql), or Apex implementation (use sf-apex).
fabric-cli
IncludedUse this skill for Fabric.so CLI workflows with the `fabric` terminal command: diagnose/install/login, search or browse a Fabric library, save notes/links/files, create folders, ask the Fabric AI assistant, manage tasks/workspaces, generate shell completion, check subscription usage, produce JSON output, and use Fabric as persistent agent memory. Do not use for Microsoft Fabric/Azure/Power BI `fab`, Daniel Miessler's Fabric framework, Python Fabric SSH, Fabric.js, or textile/fashion fabric.
lark
IncludedLark/Feishu CLI skills: lark-cli operations for docs, markdown, sheets, base, calendar, im, mail, task, okr, drive, wiki, slides, whiteboard, apps, approval, attendance, contact, vc, minutes, event. Use when the user needs to operate Lark/Feishu resources via lark-cli, send messages, manage documents, spreadsheets, calendars, tasks, OKRs, deploy web pages, or any Feishu/Lark workspace operations.