Kubernetes patterns

From j4flmao/agent-skills · View interactive version

Kubernetes patterns is an AI agent skill from the GitHub repository j4flmao/agent-skills. Use when the user asks about sidecar or native sidecar containers, ambassador/adapter/init patterns, PodDisruptionBudget, topology spread, pod anti-affinity, taints and tolerations, graceful shutdown, or ValidatingAdmissionPolicy. Produces current-API workload YAML. Not for control-plane internals (

How to use this skill

Skill file

Kubernetes Workload Patterns

Purpose

Design pods and their placement so workloads survive node drains, zone failures, and rollouts with zero dropped requests. Uses current stable APIs: native sidecar containers, policy/v1 PodDisruptionBudgets, topology spread constraints, and CEL-based ValidatingAdmissionPolicy.

Agent Protocol

Trigger

"k8s patterns", "sidecar", "native sidecar", "ambassador", "PDB", "topology spread", "anti-affinity", "taints", "graceful shutdown", "admission webhook", "ValidatingAdmissionPolicy".

Input Context

Output Artifact

Annotated manifests. No file unless requested.

Response Format

Pattern: {name} — why
Manifest: {YAML}
Failure mode covered: {node drain|zone loss|rollout|bad config}

Completion Criteria

Structural Patterns

| Pattern | Use | Implementation |

|---|---|---|

| Init container | One-shot setup before app starts (migrations check, config render) | initContainers (run to completion, in order) |

| Sidecar | Helper running alongside app for pod lifetime (proxy, log shipper, OTel agent) | Native sidecar: init container with restartPolicy: Always — starts before app, stays up, stopped after app, doesn't block Job completion |

| Ambassador | Sidecar proxying outbound calls (retries, mTLS, connection pooling) | Envoy/Cloud SQL Auth Proxy as native sidecar |

| Adapter | Normalizes app output (metrics format, logs) | Exporter sidecar |

spec:
  initContainers:
    - name: cloud-sql-proxy
      image: gcr.io/cloud-sql-connectors/cloud-sql-proxy:2.14.1
      restartPolicy: Always            # native sidecar
      args: ["--port=5432", "my-project:europe-west1:orders-db"]
      startupProbe:
        tcpSocket: { port: 5432 }
      resources:
        requests: { cpu: 50m, memory: 64Mi }
  containers:
    - name: app
      image: registry.example.com/orders:1.12.0

Resilience and Placement

apiVersion: apps/v1
kind: Deployment
metadata: { name: api }
spec:
  replicas: 6
  selector: { matchLabels: { app: api } }
  strategy:
    rollingUpdate: { maxUnavailable: 0, maxSurge: 25% }
  template:
    metadata: { labels: { app: api } }
    spec:
      topologySpreadConstraints:
        - maxSkew: 1
          topologyKey: topology.kubernetes.io/zone
          whenUnsatisfiable: DoNotSchedule
          labelSelector: { matchLabels: { app: api } }
        - maxSkew: 1
          topologyKey: kubernetes.io/hostname
          whenUnsatisfiable: ScheduleAnyway
          labelSelector: { matchLabels: { app: api } }
      terminationGracePeriodSeconds: 45
      containers:
        - name: api
          image: registry.example.com/api:3.4.1
          ports: [{ containerPort: 8080 }]
          readinessProbe:
            httpGet: { path: /readyz, port: 8080 }
            periodSeconds: 5
          livenessProbe:
            httpGet: { path: /livez, port: 8080 }
            periodSeconds: 10
            failureThreshold: 3
          lifecycle:
            preStop:
              sleep: { seconds: 10 }   # built-in sleep action (beta, on by default since 1.30; GA in 1.34); use exec sleep on older clusters
          resources:
            requests: { cpu: 250m, memory: 256Mi }
            limits: { memory: 256Mi }
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: { name: api }
spec:
  maxUnavailable: 1
  selector: { matchLabels: { app: api } }

Graceful Shutdown Sequence

  1. Pod marked Terminating; endpoints controller removes it from EndpointSlices (propagation to kube-proxy/ingress takes seconds).
  2. preStop hook runs (the sleep covers propagation delay so no new traffic arrives at a closing server).
  3. SIGTERM sent to containers; app stops accepting, drains in-flight requests, closes pools.
  4. After terminationGracePeriodSeconds (counted from step 1, including preStop), SIGKILL.

Liveness probes must not check dependencies (DB down → mass restarts). Use readiness for dependency-aware gating, startupProbe for slow boots.

Admission Control

| Need | Use |

|---|---|

| Validate fields (no root, required labels, image registry) | ValidatingAdmissionPolicy (CEL, in-process, GA in 1.30) — no webhook to operate |

| Mutate/inject (sidecars, defaults) | MutatingAdmissionWebhook, or MutatingAdmissionPolicy (CEL; beta in recent releases) |

| Rich policy library, reports | Kyverno or OPA Gatekeeper |

apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata: { name: require-nonroot }
spec:
  failurePolicy: Fail
  matchConstraints:
    resourceRules:
      - apiGroups: ["apps"]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["deployments"]
  validations:
    - expression: >-
        object.spec.template.spec.containers.all(c,
          has(c.securityContext) && has(c.securityContext.runAsNonRoot) &&
          c.securityContext.runAsNonRoot == true)
      message: "all containers must set securityContext.runAsNonRoot=true"
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata: { name: require-nonroot }
spec:
  policyName: require-nonroot
  validationActions: ["Deny"]
  matchResources:
    namespaceSelector:
      matchExpressions:
        - { key: kubernetes.io/metadata.name, operator: NotIn, values: [kube-system] }

Webhooks: set timeoutSeconds low, exclude kube-system, and run ≥2 replicas — a failurePolicy: Fail webhook that is down blocks all matching API writes.

Anti-Patterns

Checklist

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.