️ Add a couple of new-style Kyverno policies

Eventually, we should rewrite all Kyverno policies to replace
the old-style ones (ClusterPolicy) with the new ones and use CEL.
This commit is contained in:
Jérôme Petazzoni
2026-02-16 15:59:33 +01:00
parent 3e14209060
commit ae776d71ba
2 changed files with 93 additions and 0 deletions

View File

@@ -0,0 +1,56 @@
# This is a Kyverno policy to automatically generate an Ingress resource,
# similar to the other ones in this directory; but instead of using the
# "old-style" policies (ClusterPolicy with spec.rules.generate), it is
# using the new CR GeneratingPolicy and CEL.
apiVersion: policies.kyverno.io/v1
kind: GeneratingPolicy
metadata:
name: generate-ingress-for-service
spec:
matchConstraints:
resourceRules:
- apiGroups: ['']
apiVersions: ['v1']
operations: ['CREATE']
resources: ['services']
variables:
- name: host
expression: |
object.metadata.name + "." + object.metadata.namespace + ".example.com"
- name: ingress
expression: >-
[
{
"kind": dyn("Ingress"),
"apiVersion": dyn("networking.k8s.io/v1"),
"metadata": dyn({
"name": object.metadata.name,
"namespace": object.metadata.namespace,
}),
"spec": dyn({
"rules": [
{
"host": dyn(variables.host),
"http": dyn({
"paths": [
{
"path": dyn("/"),
"pathType": dyn("Prefix"),
"backend": dyn({
"service": {
"name": dyn(object.metadata.name),
"port": dyn({
"number": 80
})
}
})
}
]
})
}
]
})
}
]
generate:
- expression: generator.Apply(object.metadata.namespace, variables.ingress)

37
k8s/kyverno-vap.yaml Normal file
View File

@@ -0,0 +1,37 @@
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: ensure-security-label
spec:
# What to do if an error happens when evaluating that policy? (Fail or Ignore)
failurePolicy: Fail
matchConstraints:
resourceRules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["pods"]
scope: Namespaced # "Cluster", "Namespaced", or "*"
validations:
- expression: |
'security' in object.metadata.labels
&&
object.metadata.labels.security in [ "public", "private", "namespace" ]
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
name: ensure-security-label
spec:
policyName: ensure-security-label
# What to do when a policy doesn't validate: Deny, Warn, Audit.
# (Note: it doesn't make sense to put Deny and Warn together.)
validationActions: [ Deny ]
matchResources:
namespaceSelector:
matchExpressions:
- key: kubernetes.io/metadata.name
operator: NotIn
values: [ kube-system, local-path-storage, kyverno ]