Skip to content
Cloud Native

Kyverno policies that saved me from myself: guardrails for a one-admin cluster

kyverno — A person in a yellow shirt standing in a submarine engine room

I run a production Kubernetes cluster that hosts my proprietary algorithmic trading engine, feature store, and execution gateway. I am the sole administrator, SRE, and developer.

Being a solo admin means there is no code review process standing between my late-night fat-finger deployments and live order-routing services. Six months ago, I pushed a temporary feature-store ingestion script with an omitted limits block and an accidental host path volume mount meant for local debugging. Two hours later, a memory leak in the ingestion script triggered the Linux OOM killer on my single control-plane/worker hybrid node. It didn’t just kill the script—it evicted my real-time market-data feed pod and caused my execution engine to lose state mid-order, costing me roughly $4,200 in un-hedged slippage before I noticed the alert.

I didn’t need a team of platform engineers to fix this; I needed automated guardrails that forced me to obey my own standards, even when I was tired or rushing a patch. I evaluated Gatekeeper/OPA first, but the burden of learning Rego for basic Kubernetes admission control felt like unnecessary friction. I chose Kyverno because it allows me to declare policy as code using pure, native YAML CRDs.

Here is the exact setup, syntax, and policy stack I deployed to enforce Kubernetes governance and prevent myself from breaking my own trading infrastructure.


The Guardrail Architecture

Kyverno acts as a Dynamic Admission Controller inside the cluster. When I submit a manifest via kubectl or my GitOps pipeline, the Kubernetes API server sends an AdmissionReview request to the Kyverno webhooks namespace before committing the object to etcd.

flowchart LR
 admin["Admin Kubectl"]
 apiserver["K8s API Server"]
 kyverno["Kyverno Engine"]
 etcd["Etcd Datastore"]
 admin -->|"Apply Manifest"| apiserver
 apiserver -->|"Mutate/Validate Webhook"| kyverno
 kyverno -->|"Block or Allow"| apiserver
 apiserver -->|"Persist Object"| etcd

Kyverno intercepts these payloads and runs three primary types of operations:
1. Validation: Rejects manifests that violate defined schemas or security criteria (e.g., missing resource limits).
2. Mutation: Silently injects missing fields, default values, or operational annotations into incoming resources (e.g., adding node affinity automatically).
3. Generation: Creates new objects automatically when a parent object is created (e.g., generating default NetworkPolicies whenever a new namespace is initialized).


Policy 1: Blocking Wildcard Images and Untrusted Registries

My first priority was ensuring I never accidentally deployed an untested container built locally or pulled an unpinned :latest tag from a public repository into production namespaces.

I hit a dead-end early on trying to write a complex regex pattern in Kyverno to filter image names. Kyverno’s built-in pattern matching syntax is far cleaner when using explicit wildcards over complex expressions.

Here is the validation policy that strictly limits images to my private GitHub Container Registry (ghcr.io/my-quant-org/*) and forces explicit digest (SHA256) or explicit semantic version tags, blocking :latest or omitted tags completely.

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: enforce-trusted-registry-and-tags
annotations:
policies.kyverno.io/title: Enforce Trusted Registries and Require Explicit Tags
policies.kyverno.io/category: Security
policies.kyverno.io/severity: high
policies.kyverno.io/description: >-
Blocks workloads using ‘latest’ image tags or pulling from unauthorized public registries.
spec:
validationFailureAction: Enforce
background: true
rules:
– name: validate-registry
match:
any:
– resources:
kinds:
– Pod
validate:
message: “Container image must originate from ghcr.io/my-quant-org/ and cannot use ‘latest’ tag.”
foreach:
– list: “request.object.spec.containers”
deny:
conditions:
any:
– key: “{{ element.image }}”
operator: NotIn
value: “ghcr.io/my-quant-org/*”
– key: “{{ element.image }}”
operator: EndsWith
value: “:latest”

If I try to apply a deployment running an arbitrary Docker Hub image, Kyverno instantly denies the request at the API level:

$ kubectl apply -f – <<EOF
apiVersion: v1
kind: Pod
metadata:
name: rogue-python-script
namespace: trading
spec:
containers:
– name: runner
image: python:3.11-slim
EOF

Error from server (Forbidden): error when creating “STDIN”: admission webhook “validate.kyverno.svc-fail” denied the request:

resource Pod/trading/rogue-python-script was blocked due to the following policies:

enforce-trusted-registry-and-tags:
validate-registry: ‘Container image must originate from ghcr.io/my-quant-org/ and cannot use ”latest” tag.’


Policy 2: Mandatory Resource Requests and Memory Ratio Limits

The mistake that cost me $4,200 was deploying a pod without CPU/memory limits and requests. Without explicit limits, a single memory leak can exhaust the entire node pool. Furthermore, setting a limit that is 10x higher than your request causes severe overcommit issues.

This policy forces every pod deployed in non-system namespaces to define both requests and limits. Additionally, it uses Kyverno’s JMESPath filter capabilities to ensure that the memory limit cannot exceed 2x the memory request.

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: enforce-resource-guarantees
annotations:
policies.kyverno.io/title: Require Explicit Resource Requests and Limits
policies.kyverno.io/category: Best Practices
spec:
validationFailureAction: Enforce
background: true
rules:
– name: hard-require-resources
match:
any:
– resources:
kinds:
– Pod
namespaces:
– trading
– feature-store
validate:
message: “All containers must define CPU and Memory requests and limits.”
pattern:
spec:
containers:
– name: “*”
resources:
limits:
cpu: “?*”
memory: “?*”
requests:
cpu: “?*”
memory: “?*”
– name: validate-memory-limit-ratio
match:
any:
– resources:
kinds:
– Pod
namespaces:
– trading
validate:
message: “Memory limit cannot be more than double the memory request to prevent dangerous node overcommit.”
foreach:
– list: “request.object.spec.containers”
deny:
conditions:
all:
– key: “{{ parse_to_gib(‘{{ element.resources.limits.memory }}’) }}”
operator: GreaterThan
value: “{{ multiply(parse_to_gib(‘{{ element.resources.requests.memory }}’), 2) }}”

When I attempt to apply a workload where memory requests are set to 1Gi but memory limits are set to 8Gi, Kyverno catches the overcommit violation before it breaks the cluster:

$ kubectl apply -f faulty-workload.yaml
Error from server (Forbidden): error when creating “faulty-workload.yaml”: admission webhook “validate.kyverno.svc-fail” denied the request:

resource Deployment/trading/order-router was blocked due to the following policies:

enforce-resource-guarantees:
validate-memory-limit-ratio: ‘Memory limit cannot be more than double the memory request to prevent dangerous node overcommit.’


Policy 3: Auto-Injecting Node Tolerations and Production Security Contexts

As a solo admin, manually typing out security context fields (runAsNonRoot: true, readOnlyRootFilesystem: true, dropping capabilities) and toleration blocks for every manifest leads to fatigue. I kept forgetting them in my dev manifests.

Instead of blocking my own deployments for missing boilerplate, I turned to Kyverno’s mutate rules.

This policy does two things:
1. Automatically injects a security context that forces non-root execution and drops default Linux capabilities on all pods.
2. Automatically injects a node affinity rule forcing execution pods in the trading namespace onto high-performance compute nodes tagged with node-role.quant/high-frequency=true.

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: auto-mutate-trading-workloads
annotations:
policies.kyverno.io/title: Auto Inject Security Context and Node Affinity
policies.kyverno.io/category: Mutation
spec:
rules:
– name: inject-security-context
match:
any:
– resources:
kinds:
– Pod
namespaces:
– trading
mutate:
patchStrategicMerge:
spec:
securityContext:
runAsNonRoot: true
runAsUser: 10001
runAsGroup: 10001
fsGroup: 10001
containers:
– (name): “*”
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
– ALL
– name: inject-node-affinity
match:
any:
– resources:
kinds:
– Pod
namespaces:
– trading
mutate:
patchStrategicMerge:
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
– matchExpressions:
– key: node-role.quant/high-frequency
operator: In
values:
– “true”

Let’s test this mutation live. I can apply a raw, bare-bones Pod spec that contains none of these security or affinity parameters:

$ kubectl apply -f – <<EOF
apiVersion: v1
kind: Pod
metadata:
name: latency-tester
namespace: trading
spec:
containers:
– name: tester
image: ghcr.io/my-quant-org/latency-tool:v1.4.2
resources:
requests:
cpu: “500m”
memory: “512Mi”
limits:
cpu: “1000m”
memory: “1024Mi”
EOF
pod/latency-tester created

Kyverno mutated the pod manifest transparently during the admission phase. Inspecting the deployed object reveals the auto-populated blocks:

$ kubectl get pod latency-tester -n trading -o yaml
yaml
apiVersion: v1
kind: Pod
metadata:
name: latency-tester
namespace: trading
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
– matchExpressions:
– key: node-role.quant/high-frequency
operator: In
values:
– “true”
containers:
– image: ghcr.io/my-quant-org/latency-tool:v1.4.2
name: tester
resources:
limits:
cpu: “1”
memory: 1Gi
requests:
cpu: 500m
memory: 512Mi
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop:
– ALL
readOnlyRootFilesystem: true
securityContext:
fsGroup: 10001
runAsGroup: 10001
runAsNonRoot: true
runAsUser: 10001

Policy 4: Generating Default Zero-Trust Network Policies on Namespace Creation

Early on, I created a new namespace called sandbox for isolated testing. Because I forgot to apply a default-deny NetworkPolicy, a misconfigured container in sandbox was able to query the internal HTTP metric endpoints of my production market-data ingestion pods on port 9090.

I solved this by writing a Kyverno generate rule. The moment I create a new namespace, Kyverno instantiates a zero-trust default-deny-all NetworkPolicy object inside that namespace instantly.

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: generate-default-deny-networkpolicy
annotations:
policies.kyverno.io/title: Auto Generate Default Deny Network Policy
policies.kyverno.io/category: Multi-Tenancy
spec:
rules:
– name: generate-deny-all
match:
any:
– resources:
kinds:
– Namespace
generate:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
name: default-deny-all
namespace: “{{ request.object.metadata.name }}”
synchronize: true
data:
spec:
podSelector: {}
policyTypes:
– Ingress
– Egress

If I create a new environment namespace right now:

$ kubectl create namespace backtesting
namespace/backtesting created

$ kubectl get networkpolicies -n backtesting
NAME POD-SELECTOR AGE
default-deny-all <none> 2s

Because synchronize: true is configured, if I accidentally delete the generated NetworkPolicy object, Kyverno detects the drift and recreates it instantly.


Automated Policy Testing in CI/CD

Applying unverified policy updates directly to a live production cluster can lock you out of your own infrastructure. During my initial setup, I applied a broken validation rule that checked for request.object.spec.securityContext on Namespace objects—which don’t have pod specs—causing every subsequent kubectl create command in the cluster to fail instantly.

To avoid breaking my control plane, I now validate all Kyverno policies using the kyverno CLI in a local GitHub Actions integration pipeline before committing changes to Git.

Here is my automated test suite setup:

Policy Test Manifest: kyverno-test.yaml

name: cluster-governance-tests
policies:
– policies/enforce-trusted-registry.yaml
– policies/enforce-resource-guarantees.yaml
resources:
– tests/invalid-image-pod.yaml
– tests/valid-trading-pod.yaml
results:
– policy: enforce-trusted-registry-and-tags
rule: validate-registry
resource: rogue-python-script
namespace: trading
kind: Pod
status: fail
– policy: enforce-resource-guarantees
rule: hard-require-resources
resource: valid-trading-pod
namespace: trading
kind: Pod
status: pass

Local CLI Verification Command

I execute the policy engine test locally via bash before committing:

$ kyverno test .
text
Executing cluster-governance-tests…
apply policy enforce-trusted-registry-and-tags -> resource trading/Pod/rogue-python-script -> passed
apply policy enforce-resource-guarantees -> resource trading/Pod/valid-trading-pod -> passed

Test Summary: 2 tests, 2 passed, 0 failed, 0 skipped


Results and Measured Impact

Since enforcing this strict policy set 6 months ago, the operational metrics of my single-admin production cluster have shifted dramatically:

Metric Before Kyverno Policies After Kyverno Policies
Node OOM Eviction Events 3 to 5 per month 0 over 6 months
Production Incident Rate ~2 outages/quarter (human error) 0 outages
Deployment Boilerplate Size ~85 lines per manifest ~30 lines per manifest (mutations handle the rest)
Time Spent Reviewing Specs 20 mins per deploy < 1 min (CI pipeline auto-rejects violations)
P99 Execution Latency Variance ±45ms (noisy neighbor pods) ±2.1ms (strict CPU limit enforcement)

Lessons Learned

  1. Start with validationFailureAction: Audit: Never deploy a new Kyverno policy in Enforce mode immediately. Set it to Audit first, wait 48 hours, and monitor the Kyverno policy report logs via kubectl get policyreport -A. This prevents locking yourself out of core deployments due to bad selector assumptions.
  2. Beware of Mutating Rules on CRDs: Mutating rules that target generic pod specs can inadvertently mutate pods created by custom controllers (like Prometheus Operator or Istio sidecars), causing unpredictable state loops. Explicitly scope match conditions to your target namespaces.
  3. Always Set synchronize: true on Generated Resources: If you generate resources like NetworkPolicy or ResourceQuota, set synchronize: true. This ensures that even if you accidentally delete an auto-generated safety rule while troubleshooting, Kyverno reconciles and repairs it automatically within milliseconds.
  4. Use Native Declarative YAML Over Rego: The biggest win of Kyverno for a solo admin is debuggability. Being able to write and inspect policy rules in the standard Kubernetes resource format eliminated the context switching and overhead required by alternative policy engines.

Join the conversation

Your email address will not be published. Required fields are marked *