[{"description":"Every namespace has to carry a team label, so cost and on-call have a name.","labels":"topic:namespaces topic:labels topic:ownership topic:cost resource:namespaces engine:cel level:starter","policy":"validation","text":"A namespace without a team label has no owner: no department in the bill, nobody to call at 3am.\nThe check is one expression over the object. No other resource is involved, so CEL is enough.\napiVersion: admitik.dev/v1alpha1 kind: ClusterValidationPolicy metadata: name: require-team-label spec: failureAction: Enforce interceptedResources: - group: \"\" version: v1 resource: namespaces operations: [CREATE, UPDATE] conditions: - name: has-team engine: cel key: | has(object.metadata.labels) \u0026\u0026 \"team\" in object.metadata.labels value: \"true\" message: engine: plain template: \"namespaces need a team label, so cost and on-call have a name\" With Go templates The same check, walking the labels with a template.\napiVersion: admitik.dev/v1alpha1 kind: ClusterValidationPolicy metadata: name: require-team-label-gotmpl spec: failureAction: Enforce interceptedResources: - group: \"\" version: v1 resource: namespaces operations: - CREATE - UPDATE conditions: - name: confirm-existing-label engine: gotmpl key: | {{- $object := .object -}} {{- $labels := $object.metadata.labels -}} {{- $labelFound := false -}} {{- range $labelKey, $labelValue := $labels -}} {{- if eq $labelKey \"admitik.dev/mandatory-label\" -}} {{- $labelFound = true -}} {{- end -}} {{- end -}} {{- if $labelFound -}} {{- printf \"label-found\" -}} {{- else -}} {{- printf \"label-not-found\" -}} {{- end -}} value: \"label-found\" message: engine: gotmpl template: | {{- $object := .object -}} {{/* The following will be shown to the user on kubectl apply and logged by the controller */}} {{- printf \"Resource '%s' was rejected as some of mandatory label is missing\" .object.metadata.name -}} {{/* The following will be only logged in stdout by Admitik */}} {{- logPrintf \"Hello, this is a custom message for your SRE members\" -}} With Starlark A function per check, and the result printed for the comparison.\napiVersion: admitik.dev/v1alpha1 kind: ClusterValidationPolicy metadata: name: require-team-label-starlark spec: failureAction: Enforce interceptedResources: - group: \"\" version: v1 resource: namespaces operations: - CREATE - UPDATE conditions: - name: confirm-existing-label engine: starlark key: | def isLabelPresent(label): labels = object[\"metadata\"].get(\"labels\") if labels == None: return \"labels-not-found\" mostWanted = labels.get(label) if mostWanted == None: return \"label-not-found\" return \"label-found\" isPresent = isLabelPresent(\"admitik.dev/super-important-label\") log.debug(\"Is the label present?: \", present=isPresent) print(isPresent) value: \"label-found\" message: engine: starlark template: | print(\"Resource '{}/{}' was rejected as some required label is missing\".format(object[\"kind\"], object[\"metadata\"][\"name\"])) Notes It runs on updates too, so a namespace that already exists without the label cannot be modified until someone adds it. Drop UPDATE from the operations to limit it to new namespaces. ","title":"Require an owner label on every namespace","url":"/use-cases/require-team-label/"},{"description":"A pod that asks for privileged mode does not get created, in any namespace.","labels":"topic:security topic:containers resource:pods engine:cel level:starter","policy":"validation","text":"A privileged container has the capabilities of the node.\nThe policy intercepts pods, so it also covers the ones that Deployments, StatefulSets and Jobs create.\napiVersion: admitik.dev/v1alpha1 kind: ClusterValidationPolicy metadata: name: deny-privileged-pods spec: failureAction: Enforce interceptedResources: - group: \"\" version: v1 resource: pods operations: [CREATE, UPDATE] conditions: - name: not-privileged engine: cel key: | object.spec.containers.all(c, !has(c.securityContext) || !c.securityContext.privileged) value: \"true\" message: engine: gotmpl template: | pod {{ .object.metadata.name }} asks for privileged mode, which gives it the node Notes The denial shows on the pod, not on the Deployment that created it, because the pod is admitted before the controller finishes reconciling. The message names the pod. Naming the container needs Starlark, which can leave the offending names in vars for the message to read. ","title":"Deny privileged containers","url":"/use-cases/deny-privileged-pods/"},{"description":"One security floor for every pod of the cluster, and a rejection for the manifests that try to go below it.","labels":"topic:security topic:containers resource:pods resource:deployments engine:cel engine:starlark engine:gotmpl feature:strategicmerge feature:sources level:advanced","policy":"solution","text":"Every team writes its own manifests, and it writes them with the service in mind: the image, the port, the probe, the memory limit. The security context is not on that list. It breaks nothing when it is missing, and it is the first thing that goes in a review.\nWhat is left is a hundred workloads with a hundred different levels of isolation, and nothing in a Deployment tells them apart.\nA pod that declares no securityContext runs with the default set of the container runtime. In Docker and containerd that is 14 capabilities, and NET_RAW is one of them.\nThis solution aims at one thing: every pod runs with the same floor, whether or not its manifest mentions security, and the few that need more than the floor declare it in a place the cluster can read.\nThree policies get there. The first two patch the security context of what arrives. The third rejects what a patch cannot fix.\nThe floor is three fields:\nField Value What it does seccompProfile.type RuntimeDefault The runtime’s seccomp filter. It blocks io_uring_setup, io_uring_enter and io_uring_register allowPrivilegeEscalation false A setuid binary inside the container cannot gain capabilities the container did not have capabilities.drop [\"ALL\"] Removes the bounding set. NET_RAW, SETPCAP and MKNOD go with it A manifest that already adds a capability keeps it. The patch only writes drop.\nPatch the pod templates The first policy intercepts the four kinds that carry a pod template: deployments, statefulsets, daemonsets and jobs. All of them keep it at spec.template.spec.\napiVersion: admitik.dev/v1alpha1 kind: ClusterMutationPolicy metadata: name: harden-pod-templates spec: priority: 10 interceptedResources: - group: apps version: v1 resource: deployments operations: [CREATE, UPDATE] - group: apps version: v1 resource: statefulsets operations: [CREATE, UPDATE] - group: apps version: v1 resource: daemonsets operations: [CREATE, UPDATE] - group: batch version: v1 resource: jobs operations: [CREATE, UPDATE] patch: type: strategicmerge engine: starlark template: | def harden(containers): return [{\"name\": c[\"name\"], \"securityContext\": {\"allowPrivilegeEscalation\": False, \"capabilities\": {\"drop\": [\"ALL\"]}}} for c in (containers or [])] spec = object[\"spec\"][\"template\"][\"spec\"] pod = {\"securityContext\": {\"seccompProfile\": {\"type\": \"RuntimeDefault\"}}, \"containers\": harden(spec[\"containers\"]), \"initContainers\": harden(spec.get(\"initContainers\"))} print(yaml.encode({\"spec\": {\"template\": {\"spec\": pod}}})) strategicmerge merges the container list by name and leaves the rest of each container alone: image, ports, env, resources and the securityContext fields the team already set. yaml.encode prints the dictionary as the patch document.\nPatch the pods Not every pod comes from a template. Bare pods, kubectl run, CronJobs and the controllers that build their own pods never pass through one, and the first policy does not see them.\napiVersion: admitik.dev/v1alpha1 kind: ClusterMutationPolicy metadata: name: harden-pods spec: priority: 20 interceptedResources: - group: \"\" version: v1 resource: pods operations: [CREATE, UPDATE] patch: type: strategicmerge engine: starlark template: | def harden(containers): return [{\"name\": c[\"name\"], \"securityContext\": {\"allowPrivilegeEscalation\": False, \"capabilities\": {\"drop\": [\"ALL\"]}}} for c in (containers or [])] spec = object[\"spec\"] pod = {\"securityContext\": {\"seccompProfile\": {\"type\": \"RuntimeDefault\"}}, \"containers\": harden(spec[\"containers\"]), \"initContainers\": harden(spec.get(\"initContainers\"))} print(yaml.encode({\"spec\": pod})) The two policies run in order. A pod created by a Deployment arrives already patched, and the second policy finds nothing to change.\nCronJobs are the one gap. Their template lives at spec.jobTemplate.spec.template.spec, which is neither of the two paths, so the second policy covers their pods and not their template.\nBefore and after This is the Deployment a team writes:\napiVersion: apps/v1 kind: Deployment metadata: name: payments-api namespace: payments spec: replicas: 3 selector: matchLabels: app: payments-api template: metadata: labels: app: payments-api spec: containers: - name: api image: registry.admitik.dev/payments/api:1.4.2 ports: - containerPort: 8080 resources: limits: memory: 512Mi The same Deployment once stored. The image, the ports and the limits are the ones the team wrote, and the three fields are there:\nspec: template: spec: securityContext: seccompProfile: type: RuntimeDefault containers: - name: api image: registry.admitik.dev/payments/api:1.4.2 ports: - containerPort: 8080 resources: limits: memory: 512Mi securityContext: allowPrivilegeEscalation: false capabilities: drop: [\"ALL\"] What a patch cannot fix The mutation empties the capability set, but it cannot refuse a request. A manifest that puts SYS_ADMIN back keeps it: the container ends up with drop: [\"ALL\"] and add: [\"SYS_ADMIN\"], and runs with exactly that one capability.\nThat needs a policy that can deny. This one reads the security context of the pod and of its containers, and rejects:\nprivileged: true on any container hostNetwork, hostPID or hostIPC on the pod seccomp Unconfined, on the pod or on a container a capability added outside the baseline list of the Pod Security Standards apiVersion: admitik.dev/v1alpha1 kind: ClusterValidationPolicy metadata: name: deny-risky-security-context spec: failureAction: Enforce interceptedResources: - group: \"\" version: v1 resource: pods operations: [CREATE, UPDATE] conditions: - name: security-context engine: starlark key: | allowed = [\"AUDIT_WRITE\", \"CHOWN\", \"DAC_OVERRIDE\", \"FOWNER\", \"FSETID\", \"KILL\", \"MKNOD\", \"NET_BIND_SERVICE\", \"SETFCAP\", \"SETGID\", \"SETPCAP\", \"SETUID\", \"SYS_CHROOT\"] def seccomp_type(context): return ((context or {}).get(\"seccompProfile\") or {}).get(\"type\") def problems(): spec = object[\"spec\"] found = [] for field in [\"hostNetwork\", \"hostPID\", \"hostIPC\"]: if spec.get(field): found.append(field) if seccomp_type(spec.get(\"securityContext\")) == \"Unconfined\": found.append(\"pod seccomp Unconfined\") for container in (spec.get(\"containers\") or []) + (spec.get(\"initContainers\") or []): context = container.get(\"securityContext\") or {} if context.get(\"privileged\"): found.append(\"%s is privileged\" % container[\"name\"]) if seccomp_type(context) == \"Unconfined\": found.append(\"%s seccomp Unconfined\" % container[\"name\"]) for capability in (context.get(\"capabilities\") or {}).get(\"add\") or []: name = capability.upper().replace(\"CAP_\", \"\") if name not in allowed: found.append(\"%s adds %s\" % (container[\"name\"], name)) return found found = problems() vars[\"problems\"] = \", \".join(found) print(\"clean\" if not found else \"failed\") value: clean message: engine: gotmpl template: | {{ .object.metadata.namespace }}/{{ .object.metadata.name }}: {{ .vars.problems }} The message names everything the pod got wrong, not just the first thing.\nWith that policy in place, a pod that adds a capability outside the list does not get created:\napiVersion: v1 kind: Pod metadata: name: debug namespace: payments spec: containers: - name: shell image: registry.admitik.dev/tools/shell:1 securityContext: capabilities: add: [\"SYS_ADMIN\"] Error from server: error when creating \"debug.yaml\": admission webhook \"validate.admitik.dev\" denied the request: payments/debug: shell adds SYS_ADMIN The namespaces that ask for more Not every workload fits the same shape. runAsNonRoot breaks an image that starts as root: the kubelet refuses to start the container, with CreateContainerConfigError. readOnlyRootFilesystem breaks any image that writes to /var. Neither belongs in a floor applied to every namespace, so they live in a policy of their own, and a namespace opts in with a label:\napiVersion: admitik.dev/v1alpha1 kind: ClusterValidationPolicy metadata: name: restricted-namespaces spec: failureAction: Permissive interceptedResources: - group: \"\" version: v1 resource: pods operations: [CREATE, UPDATE] sources: - group: \"\" version: v1 resource: namespaces filters: name: matchList: [\"{{cel: object.metadata.namespace }}\"] metadata: matchLabels: admitik.dev/security: restricted conditions: - name: non-root engine: cel key: | sources[0].size() == 0 || object.spec.containers.all(c, has(c.securityContext) \u0026\u0026 has(c.securityContext.runAsNonRoot) \u0026\u0026 c.securityContext.runAsNonRoot == true) value: \"true\" message: engine: plain template: containers in a restricted namespace run as non-root The source returns the namespace only when it carries the label, so an empty sources[0] is a namespace that did not opt in. readOnlyRootFilesystem and hostUsers take one condition each, with the same shape.\nRolling it out The two mutations go first. They rewrite the security context and reject nothing, so a workload that runs today keeps running.\nThey apply at admission. A pod that is already running keeps the security context it was created with until its next restart, so a rolling restart is what moves the cluster to the new floor.\nThe validation is the one to turn on slowly. failureAction: Permissive first, for a week: the warnings land in the audit log and in kubectl output, and they name the workloads that would have been rejected:\nWarning: payments/worker: worker adds NET_ADMIN Then Enforce.\nNotes seccompProfile: Localhost needs the profile file at the same path on every node. A pod whose profile is missing does not start, so the policy uses RuntimeDefault. A seccompProfile on a single container wins over the one the mutation sets on the pod. The validation reads both. A pod with no init containers still gets initContainers: [] in the patch. The list is empty, and strategicmerge leaves the field as it was. Both mutations intercept UPDATE as well as CREATE. Without it, an edit that removes the security context would be stored, and the template would stop describing what runs. The checks that read several optional fields are Starlark. In CEL, each of those fields needs a has() in front, and the rule disappears behind them. AppArmor is out of scope here. The field is securityContext.appArmorProfile, and older clusters still carry the container.apparmor.security.beta.kubernetes.io/\u003ccontainer\u003e annotation. ","title":"A hardened security context on every pod","url":"/use-cases/harden-pod-security-context/"},{"description":"Namespaces get the labels the platform reads, without asking anyone to remember them.","labels":"topic:namespaces topic:labels topic:defaults resource:namespaces engine:plain level:starter","policy":"mutation","text":"Labels that the platform reads are labels people forget.\napiVersion: admitik.dev/v1alpha1 kind: ClusterMutationPolicy metadata: name: default-namespace-labels spec: priority: 10 interceptedResources: - group: \"\" version: v1 resource: namespaces operations: [CREATE] patch: type: jsonmerge engine: plain template: | metadata: labels: managed-by: platform admitik.dev/tier: standard With Plain + CEL plain+cel keeps the patch readable and lets one value come from the object.\napiVersion: admitik.dev/v1alpha1 kind: ClusterMutationPolicy metadata: name: default-namespace-labels-cel spec: interceptedResources: - group: \"\" version: v1 resource: namespaces operations: - CREATE patch: type: jsonmerge # JsonPatch | JsonMerge | StrategicMerge engine: plain+cel template: | metadata: labels: patch-01-custom-label/namespace: \"{{cel: object.metadata.name }}\" With a strategic merge A strategic merge needs the whole object, not only the part that changes.\napiVersion: admitik.dev/v1alpha1 kind: ClusterMutationPolicy metadata: name: default-namespace-labels-strategic spec: interceptedResources: - group: \"\" version: v1 resource: namespaces operations: - CREATE patch: type: strategicmerge # JsonPatch | JsonMerge | StrategicMerge engine: plain+cel template: | apiVersion: v1 kind: Namespace metadata: labels: patch-07-custom-label/namespace: \"{{cel: object.metadata.name }}\" Notes jsonmerge merges into what the namespace already has. A managed-by already set by the team stays. If the platform value has to win, reject the other one with a validation policy instead of patching over it. Mutations run by priority and then by name. Ten leaves room for the policies that have to run before this one. ","title":"Add platform labels to every namespace","url":"/use-cases/add-default-labels/"},{"description":"Annotations that record who owns a namespace or what touched it, without asking anyone to write them.","labels":"topic:namespaces topic:annotations topic:defaults resource:namespaces engine:plain+cel engine:starlark level:intermediate","policy":"mutation","text":"Annotations that say who owns a namespace, or which policy touched it, are the first thing people skip when they create one by hand.\nCreating the map when it is missing jsonpatch cannot add a key to a map that does not exist, so the patch adds the map first. The condition only lets through the namespaces without annotations.\napiVersion: admitik.dev/v1alpha1 kind: ClusterMutationPolicy metadata: name: namespace-annotations-create spec: interceptedResources: - group: \"\" version: v1 resource: namespaces operations: - CREATE conditions: - name: ensure-annotations-missing engine: cel key: '!has(object.metadata.annotations)' value: \"true\" patch: type: jsonpatch # JsonPatch | JsonMerge | StrategicMerge engine: plain+cel template: | [ { \"op\": \"add\", \"path\": \"/metadata/annotations\", \"value\": {} }, { \"op\": \"add\", \"path\": \"/metadata/annotations/patch-03-hello\", \"value\": \"world\" } ] Adding to an existing map With the map in place, each operation writes one key from a value of the object.\napiVersion: admitik.dev/v1alpha1 kind: ClusterMutationPolicy metadata: name: namespace-annotations-add spec: interceptedResources: - group: \"\" version: v1 resource: namespaces operations: - CREATE conditions: - name: ensure-annotations-exist engine: cel key: has(object.metadata.annotations) value: \"true\" patch: type: jsonpatch # JsonPatch | JsonMerge | StrategicMerge engine: plain+cel template: | [ { \"op\": \"add\", \"path\": \"/metadata/annotations/patch-04-object-operation\", \"value\": \"{{cel: operation }}\" }, { \"op\": \"add\", \"path\": \"/metadata/annotations/patch-04-object-kind\", \"value\": \"{{cel: object.kind }}\" }, { \"op\": \"add\", \"path\": \"/metadata/annotations/patch-04-object-name\", \"value\": \"{{cel: object.metadata.name }}\" } ] Building the patch in code Starlark decides the operations itself and encodes the list, which is what jsonpatch expects.\napiVersion: admitik.dev/v1alpha1 kind: ClusterMutationPolicy metadata: name: namespace-annotations-starlark spec: interceptedResources: - group: \"\" version: v1 resource: namespaces operations: - CREATE - UPDATE conditions: - name: first-condition engine: starlark key: | def check_namespace(): if object[\"metadata\"][\"name\"].startswith(\"mutate-\"): print(\"mutate-it\") check_namespace() value: \"mutate-it\" patch: type: jsonpatch # JsonPatch | JsonMerge | StrategicMerge engine: starlark template: | def check_operation(): patch = [] if \"annotations\" not in object[\"metadata\"]: patch = patch + [{\"op\": \"add\", \"path\": \"/metadata/annotations\", \"value\": {}}] if operation == \"CREATE\": patch = patch + [ {\"op\": \"add\", \"path\": \"/metadata/annotations/patch-06-mutated-by\", \"value\": \"admitik\"} ] else: patch = patch + [] print(json.encode(patch)) check_operation() ","title":"Add annotations to every namespace","url":"/use-cases/annotations-on-namespaces/"},{"description":"A namespace gets its platform ConfigMap the moment it exists, without a controller of your own.","labels":"topic:configmaps topic:namespaces topic:bootstrap resource:configmaps resource:namespaces engine:gotmpl level:intermediate","policy":"generation","text":"Every namespace needs the same small ConfigMap: the log endpoint, the cluster name, the region. Done by hand, it is a step in a checklist that half the teams skip.\napiVersion: admitik.dev/v1alpha1 kind: ClusterGenerationPolicy metadata: name: platform-config spec: overwriteExisting: true deletionPolicy: Delete watchedResources: - group: \"\" version: v1 resource: namespaces conditions: - name: skip-system-namespaces engine: cel key: | !(object.metadata.name in [\"kube-system\", \"kube-public\", \"kube-node-lease\"]) value: \"true\" object: definition: engine: gotmpl template: | apiVersion: v1 kind: ConfigMap metadata: name: platform namespace: {{ .object.metadata.name }} data: CLUSTER: \"prod-eu-1\" LOG_ENDPOINT: \"https://logs.internal/ingest\" Fixed values When nothing has to be computed, a plain definition is the whole manifest.\napiVersion: admitik.dev/v1alpha1 kind: ClusterGenerationPolicy metadata: name: platform-config-fixed spec: overwriteExisting: true watchedResources: - group: \"\" version: v1 resource: namespaces conditions: - name: first-condition engine: cel key: | object.metadata.name value: \"default\" object: clone: {} definition: engine: plain template: | apiVersion: v1 kind: ConfigMap metadata: name: whatever-config-plain namespace: \"default\" data: FIRST_SOURCE_ITEM_NAME: \"fixed-value\" FIRST_SOURCE_ITEM_NAMESPACE: \"fixed-value-other\" With a source and plain+cel The namespace comes from the event and the first data key from a source.\napiVersion: admitik.dev/v1alpha1 kind: ClusterGenerationPolicy metadata: name: platform-config-cel spec: overwriteExisting: true watchedResources: - group: \"\" version: v1 resource: namespaces sources: - group: \"\" version: v1 resource: configmaps conditions: - name: first-condition engine: cel key: | object.metadata.name value: \"default\" object: clone: {} definition: engine: plain+cel template: | apiVersion: v1 kind: ConfigMap metadata: name: whatever-config namespace: \"{{cel: object.metadata.name }}\" data: FIRST_SOURCE_ITEM_NAME: \"{{cel: sources[0][0].metadata.name }}\" FIRST_SOURCE_ITEM_NAMESPACE: \"{{cel: sources[0][0].metadata.namespace }}\" Notes overwriteExisting: true writes the ConfigMap again on every event on the namespace, which overwrites a hand edit. deletionPolicy: Delete removes the generated ConfigMaps when the policy is removed. The admitik.dev/policy label is what finds them. ","title":"Generate a ConfigMap in every new namespace","url":"/use-cases/generate-configmap-per-namespace/"},{"description":"Two routes with the same hostname and path are a bug that only shows up in production traffic.","labels":"topic:routing topic:gateway-api resource:httproutes engine:starlark feature:sources feature:vars level:advanced","policy":"validation","text":"Two HTTPRoute objects can declare the same hostname and path. The API accepts both, the gateway serves one, and the other stops receiving traffic without saying so.\nComparing the incoming route with the existing ones needs a loop, so the condition is Starlark and the whole list of routes is a source.\napiVersion: admitik.dev/v1alpha1 kind: ClusterValidationPolicy metadata: name: avoid-colliding-routes spec: failureAction: Permissive interceptedResources: - group: gateway.networking.k8s.io version: v1 resource: httproutes operations: - CREATE - UPDATE sources: - group: gateway.networking.k8s.io version: v1 resource: httproutes conditions: - name: compute-raw-match engine: starlark key: | def compute_raw_match(): incoming_route = object existing_routes = sources[0] incoming_name = incoming_route[\"metadata\"][\"name\"] incoming_namespace = incoming_route[\"metadata\"][\"namespace\"] incoming_parent_refs = incoming_route[\"spec\"][\"parentRefs\"] incoming_hostnames = incoming_route[\"spec\"][\"hostnames\"] for existing_route in existing_routes: if (incoming_name == existing_route[\"metadata\"][\"name\"] and incoming_namespace == existing_route[\"metadata\"][\"namespace\"]): continue if not has_matching_parent_ref(incoming_parent_refs, existing_route[\"spec\"][\"parentRefs\"]): continue matching_hostnames = [h for h in incoming_hostnames if h in existing_route[\"spec\"][\"hostnames\"]] if not matching_hostnames: continue if path_conflict_exists(incoming_route, existing_route): vars[\"existing_route\"] = { \"name\": existing_route[\"metadata\"][\"name\"], \"namespace\": existing_route[\"metadata\"][\"namespace\"] } break return \"ignore-condition\" def has_matching_parent_ref(incoming_refs, existing_refs): \"\"\"Check if any parent references match between routes\"\"\" for inc_ref in incoming_refs: inc_name = inc_ref[\"name\"] inc_namespace = inc_ref.get(\"namespace\") for ex_ref in existing_refs: if (inc_name == ex_ref[\"name\"] and inc_namespace == ex_ref.get(\"namespace\")): return True return False def path_conflict_exists(incoming_route, existing_route): \"\"\"Check if there's a path conflict between routes\"\"\" for inc_rule in incoming_route[\"spec\"][\"rules\"]: for inc_match in inc_rule[\"matches\"]: inc_path_type = inc_match[\"path\"][\"type\"] if inc_path_type not in [\"Exact\", \"PathPrefix\"]: continue inc_path = inc_match[\"path\"][\"value\"].rstrip(\"/\") inc_headers = inc_match.get(\"headers\", []) for ex_rule in existing_route[\"spec\"][\"rules\"]: for ex_match in ex_rule[\"matches\"]: ex_path_type = ex_match[\"path\"][\"type\"] if ex_path_type != inc_path_type: continue ex_path = ex_match[\"path\"][\"value\"].rstrip(\"/\") if inc_path == ex_path: vars[\"headers_to_check\"] = { \"incoming\": inc_headers, \"existing\": ex_match.get(\"headers\", []) } return True return False compute_raw_match() print(\"ignore-condition\") value: ignore-condition - name: check-headers-not-matching engine: starlark key: | log.debug(\"Debug purposes: vars content: \", variables=vars) def check_headers_not_matching(): headers_to_check = vars.get(\"headers_to_check\", {}) if not headers_to_check: return \"path-headers-unique\" incoming_headers = headers_to_check.get(\"incoming\", []) existing_headers = headers_to_check.get(\"existing\", []) if len(incoming_headers) == 0 and len(existing_headers) == 0: return \"path-headers-duplicated\" if len(incoming_headers) != len(existing_headers): return \"path-headers-unique\" for inc_header in incoming_headers: match_found = False inc_name = inc_header[\"name\"] inc_type = inc_header.get(\"type\", \"Exact\") inc_value = inc_header[\"value\"] for ex_header in existing_headers: ex_type = ex_header.get(\"type\", \"Exact\") if (inc_name == ex_header[\"name\"] and inc_type == ex_type and inc_value == ex_header[\"value\"]): match_found = True break if not match_found: return \"path-headers-unique\" return \"path-headers-duplicated\" evaluation_result = check_headers_not_matching() print(evaluation_result) value: path-headers-unique message: engine: starlark template: | def format_message(): existing_route = vars.get(\"existing_route\", {}) return \"Resource '{}' has some declared routes already existing in object '{}/{}'\".format( object[\"metadata\"][\"name\"], existing_route.get(\"namespace\", \"\"), existing_route.get(\"name\", \"\") ) print(format_message()) Notes same_object, shares_parent, shares_hostname and shared_paths are defined inside the template, so the policy is the whole file. It ships as Permissive. Run it that way first, read the warnings, and switch to Enforce once the routes that already collide are fixed. ","title":"Reject HTTPRoutes that collide with an existing one","url":"/use-cases/avoid-colliding-httproutes/"},{"description":"A namespace declares its ceiling, and every Deployment that lands in it is capped to it.","labels":"topic:cost topic:replicas resource:deployments resource:namespaces engine:starlark feature:sources feature:vars feature:jsonmerge level:intermediate","policy":"mutation","text":"A team scales a Deployment to forty replicas and the node pool empties. The ceiling lives in a spreadsheet.\nThe policy reads the namespace of the incoming Deployment, takes max-replicas from its labels and lowers spec.replicas when the request goes over it.\napiVersion: admitik.dev/v1alpha1 kind: ClusterMutationPolicy metadata: name: cap-replicas spec: priority: 20 interceptedResources: - group: apps version: v1 resource: deployments operations: [CREATE, UPDATE] sources: - group: \"\" version: v1 resource: namespaces filters: metadata: matchLabels: admitik.dev/enforce-replica-cap: \"true\" conditions: - name: ceiling-declared engine: starlark key: | namespace = next((n for n in sources[0] if n[\"metadata\"][\"name\"] == object[\"metadata\"][\"namespace\"]), None) if namespace and \"max-replicas\" in namespace[\"metadata\"].get(\"labels\", {}): vars[\"ceiling\"] = int(namespace[\"metadata\"][\"labels\"][\"max-replicas\"]) print(\"ceiling\") else: print(\"no-ceiling\") value: ceiling patch: type: jsonmerge engine: starlark template: | replicas = object[\"spec\"].get(\"replicas\", 1) ceiling = vars[\"ceiling\"] if replicas \u003e ceiling: print({\"spec\": {\"replicas\": ceiling}}) else: print({}) Notes The source filter keeps only the namespaces that opted in. Starlark for the condition: the namespace has to be found in a list. It leaves the ceiling in vars and the patch reads it back. Without max-replicas the condition does not match and nothing happens. The policy lowers a request, it does not audit. ","title":"Cap the replicas of a Deployment with a namespace label","url":"/use-cases/cap-replicas-from-namespace/"},{"description":"A label that carries a count computed from another resource, filtered to the namespace of the object.","labels":"topic:namespaces topic:labels topic:configmaps resource:namespaces engine:plain+cel feature:sources level:intermediate","policy":"mutation","text":"A source is not only for conditions: the patch can read it too. Here the label carries the number of ConfigMaps in the namespace, and the source filter uses a value of the incoming object.\napiVersion: admitik.dev/v1alpha1 kind: ClusterMutationPolicy metadata: name: namespace-configmaps-count spec: interceptedResources: - group: \"\" version: v1 resource: namespaces operations: - CREATE sources: - group: \"\" version: v1 resource: configmaps filters: namespace: matchList: - kube-system - \"{{cel: object.metadata.name }}\" conditions: - name: ensure-labels-exist engine: cel key: has(object.metadata.labels) value: \"true\" patch: type: jsonpatch # JsonPatch | JsonMerge | StrategicMerge engine: plain+cel template: | [ { \"op\": \"add\", \"path\": \"/metadata/labels/patch-05-configmaps-count\", \"value\": \"{{cel: sources[0].size() }}\" } ] Notes The filter has \"{{cel: object.metadata.name }}\" in its namespace list, so each namespace reads its own ConfigMaps instead of the whole cluster. sources[0].size() counts the objects the source returned. ","title":"Write the size of a source into a label","url":"/use-cases/write-a-source-count-in-a-label/"},{"description":"Three policies that generate the FluentBit configuration, point the pod template at it and inject the sidecar.","labels":"topic:logging topic:sidecars topic:configmaps resource:deployments resource:pods engine:cel engine:starlark level:advanced","policy":"solution","text":"Every team that wants centralized logs has to add a log shipper to its own manifests, and every team does it differently. This is three policies that do it for them.\nA workload opts in with two annotations. From there, Admitik generates the FluentBit configuration for its containers, puts the name of that ConfigMap in the pod template and injects the sidecar.\nmetadata: labels: admitik.policy.v1/logging: \"true\" annotations: admitik.policy.v1/loggingConfig: | - container: \"app\" parser: \"json\" index: \"my-app-logs\" host: \"fluentd.logging.svc.cluster.local\" port: \"24224\" - container: \"nginx\" parser: \"nginx\" index: \"nginx-logs\" loggingConfig One entry per container. Anything the entry sets ends up as a record field that FluentD reads.\nField What it is Default container The container whose logs are read required index The index on the receiving side required parser The FluentD parser for those logs json ilm_policy_id Retention policy of the index 30d ingest_anyways Forward logs that fail to parse true host Where the sidecar sends them fluentd.logging.svc.cluster.local port Port of that host 24224 1. Generate the ConfigMap Watches the workloads, reads the annotation and writes one fluentbit_\u003ccontainer\u003e.conf per entry.\n# logging-generate-fluentbit-configmap-v1 is a policy that generates a fluentbit configmap for deployments, # daemonsets, statefulsets and cronjobs which have the label admitik.policy.v1/logging set to true and the annotation # admitik.policy.v1/loggingConfig set to a valid yaml configuration. # This configmap is used to configure the fluentbit sidecar in the pods and send the logs to a fluentd instance. apiVersion: admitik.dev/v1alpha1 kind: ClusterGenerationPolicy metadata: name: logging-generate-fluentbit-configmap-v1 spec: overwriteExisting: true watchedResources: - group: apps version: v1 resource: deployments - group: apps version: v1 resource: daemonsets - group: apps version: v1 resource: statefulsets - group: batch version: v1 resource: cronjobs - group: argoproj.io version: v1alpha1 resource: rollouts sources: [] conditions: - name: apply-on-specific-mark engine: cel key: | (has(object.metadata.labels) \u0026\u0026 object.metadata.labels.exists(label, label == 'admitik.policy.v1/logging')) || (has(object.metadata.annotations) \u0026\u0026 object.metadata.annotations.exists(label, label == 'admitik.policy.v1/logging')) \u0026\u0026 (has(object.metadata.annotations) \u0026\u0026 object.metadata.annotations.exists(label, label == 'admitik.policy.v1/loggingConfig')) value: \"true\" object: clone: {} definition: engine: starlark template: | def generate_configmap(): configmap_data_section = { \"fluentbit.conf\": \"\"\" [SERVICE] Flush 1 Log_Level info Daemon off @INCLUDE /fluent-bit/etc/fluentbit_*.conf \"\"\" } for entry in yaml.decode(object[\"metadata\"][\"annotations\"][\"admitik.policy.v1/loggingConfig\"]): namespace = object[\"metadata\"][\"namespace\"] container = entry.get(\"container\") parser = entry.get(\"parser\", \"json\") index = entry.get(\"index\") ilm = entry.get(\"ilm_policy_id\", \"30d\") ingest_anyways = entry.get(\"ingest_anyways\", \"true\") host = entry.get(\"host\", \"fluentd.logging.svc.cluster.local\") port = entry.get(\"port\", \"24224\") content = \"\"\" [INPUT] Name tail Path /var/log/containers/${{HOSTNAME}}_{}_{}-*.log multiline.parser docker, cri Tag {}.{} Mem_Buf_Limit 25MB Skip_Long_Lines On Refresh_Interval 5 db /fluent-bit/pos/{}.db [FILTER] Name record_modifier Match {}.{} Record index \"{}\" Record pod_name \"${{HOSTNAME}}\" Record namespace \"{}\" Record container \"{}\" Record ilm_policy_id \"{}\" Record ingest_anyways \"{}\" [OUTPUT] Name forward Match {}.{} Host {} Port {} Retry_Limit 5\"\"\".format(namespace, container, container, parser, container, container, parser, index, namespace, container, ilm, ingest_anyways, container, parser, host, port) configmap_data_section[\"fluentbit_\" + container + \".conf\"] = content configmap_resource = { \"apiVersion\": \"v1\", \"kind\": \"ConfigMap\", \"metadata\": { \"name\": \"fluentbit-\" + object[\"metadata\"][\"name\"] + \"-autogenerated\", \"namespace\": object[\"metadata\"][\"namespace\"], \"labels\": { \"managed-by\": \"admitik\", \"policy-name\": \"logging-generate-fluentbit-configmap-v1\", \"parent-object-kind\": object[\"kind\"], \"parent-object-name\": object[\"metadata\"][\"name\"] }, }, \"data\": configmap_data_section } return configmap_resource print(generate_configmap()) 2. Point the pod template at it Writes the name of the generated ConfigMap into the pod template, and copies the sidecar resources from admitik.policy.v1/loggingSidecarResources to admitik.policy.v1/fluentbitResources.\n# logging-mutate-fluentbit-configmap-name-v1 is a policy that adds the name of the fluentbit configmap for the pods created by # deployments, daemonsets, statefulsets and cronjobs which have the label admitik.policy.v1/logging set to true and the annotation # admitik.policy.v1/loggingConfig set to a valid yaml configuration. # This policy adds the name of the configmap to the annotations of the child object. # If the admitik.policy.v1/loggingSidecarResources annotation is present, it will be propagated as admitik.policy.v1/fluentbitResources to the pod template. apiVersion: admitik.dev/v1alpha1 kind: ClusterMutationPolicy metadata: name: logging-mutate-fluentbit-configmap-name-v1 spec: # Resources to be intercepted before reaching the cluster interceptedResources: - group: apps version: v1 resource: deployments operations: - CREATE - UPDATE - group: apps version: v1 resource: daemonsets operations: - CREATE - UPDATE - group: apps version: v1 resource: statefulsets operations: - CREATE - UPDATE - group: argoproj.io version: v1alpha1 resource: rollouts operations: - CREATE - UPDATE # Other resources to be retrieved for conditions templates. # They will be included under .sources scope in the template sources: [] # Conditions are optional, so no-conditions means they are always met conditions: - name: apply-on-specific-mark engine: cel key: | (has(object.metadata.labels) \u0026\u0026 object.metadata.labels.exists(label, label == 'admitik.policy.v1/logging')) || (has(object.metadata.annotations) \u0026\u0026 object.metadata.annotations.exists(label, label == 'admitik.policy.v1/logging')) value: \"true\" patch: type: jsonpatch # JsonPatch | JsonMerge engine: starlark template: | def check_operation(): patch = [] if \"annotations\" not in object[\"spec\"][\"template\"][\"metadata\"]: patch = patch + [{\"op\": \"add\", \"path\": \"/spec/template/metadata/annotations\", \"value\": {}}] patch = patch + [ {\"op\": \"add\", \"path\": \"/spec/template/metadata/annotations/admitik.policy.v1~1fluentbitConfigmap\", \"value\": \"fluentbit-\" + object[\"metadata\"][\"name\"] + \"-autogenerated\" }, {\"op\": \"add\", \"path\": \"/spec/template/metadata/annotations/admitik.policy.v1~1fluentbitConfigmapHash\", \"value\": hashlib.sha256(object[\"metadata\"][\"annotations\"][\"admitik.policy.v1/loggingConfig\"]) }, {\"op\": \"add\", \"path\": \"/spec/template/metadata/labels/admitik.policy.v1~1logging\", \"value\": \"true\" } ] # Add fluentbitResources annotation if loggingSidecarResources is present if object[\"metadata\"].get(\"annotations\", {}).get(\"admitik.policy.v1/loggingSidecarResources\"): entry = yaml.decode(object[\"metadata\"][\"annotations\"][\"admitik.policy.v1/loggingSidecarResources\"]) if entry.get(\"requests\"): cpuRequest = entry.get(\"requests\").get(\"cpu\", \"50m\") memoryRequest = entry.get(\"requests\").get(\"memory\", \"50Mi\") else: cpuRequest = \"50m\" memoryRequest = \"50Mi\" if entry.get(\"limits\"): memoryLimit = entry.get(\"limits\").get(\"memory\", \"100Mi\") else: memoryLimit = \"100Mi\" resources = { \"requests\": { \"cpu\": cpuRequest, \"memory\": memoryRequest }, \"limits\": { \"memory\": memoryLimit } } patch = patch + [ {\"op\": \"add\", \"path\": \"/spec/template/metadata/annotations/admitik.policy.v1~1fluentbitResources\", \"value\": json.encode(resources) } ] print(json.encode(patch)) check_operation() --- # For cronjobs, we need to mutate the jobTemplate.spec.template.metadata.annotations and labels instead of the spec.template.metadata.annotations and labels apiVersion: admitik.dev/v1alpha1 kind: ClusterMutationPolicy metadata: name: logging-mutate-fluentbit-cronjob-configmap-name-v1 spec: # Resources to be intercepted before reaching the cluster interceptedResources: - group: batch version: v1 resource: cronjobs operations: - CREATE - UPDATE # Other resources to be retrieved for conditions templates. # They will be included under .sources scope in the template sources: [] # Conditions are optional, so no-conditions means they are always met conditions: - name: apply-on-specific-mark engine: cel key: | (has(object.metadata.labels) \u0026\u0026 object.metadata.labels.exists(label, label == 'admitik.policy.v1/logging')) || (has(object.metadata.annotations) \u0026\u0026 object.metadata.annotations.exists(label, label == 'admitik.policy.v1/logging')) value: \"true\" patch: type: jsonpatch # JsonPatch | StrategicMerge engine: starlark template: | def check_operation(): patch = [] if \"annotations\" not in object[\"spec\"][\"jobTemplate\"][\"spec\"][\"template\"][\"metadata\"]: patch = patch + [{\"op\": \"add\", \"path\": \"/spec/jobTemplate/spec/template/metadata/annotations\", \"value\": {}}] patch = patch + [ {\"op\": \"add\", \"path\": \"/spec/jobTemplate/spec/template/metadata/annotations/admitik.policy.v1~1fluentbitConfigmap\", \"value\": \"fluentbit-\" + object[\"metadata\"][\"name\"] + \"-autogenerated\" }, {\"op\": \"add\", \"path\": \"/spec/jobTemplate/spec/template/metadata/labels/admitik.policy.v1~1logging\", \"value\": \"true\" } ] # Add fluentbitResources annotation if loggingSidecarResources is present if object[\"metadata\"].get(\"annotations\", {}).get(\"admitik.policy.v1/loggingSidecarResources\"): entry = yaml.decode(object[\"metadata\"][\"annotations\"][\"admitik.policy.v1/loggingSidecarResources\"]) if entry.get(\"requests\"): cpuRequest = entry.get(\"requests\").get(\"cpu\", \"50m\") memoryRequest = entry.get(\"requests\").get(\"memory\", \"50Mi\") else: cpuRequest = \"50m\" memoryRequest = \"50Mi\" if entry.get(\"limits\"): memoryLimit = entry.get(\"limits\").get(\"memory\", \"100Mi\") else: memoryLimit = \"100Mi\" resources = { \"requests\": { \"cpu\": cpuRequest, \"memory\": memoryRequest }, \"limits\": { \"memory\": memoryLimit } } patch = patch + [ {\"op\": \"add\", \"path\": \"/spec/jobTemplate/spec/template/metadata/annotations/admitik.policy.v1~1fluentbitResources\", \"value\": object[\"metadata\"][\"annotations\"][\"admitik.policy.v1/loggingSidecarResources\"] } ] print(json.encode(patch)) check_operation() 3. Inject the sidecar Adds the FluentBit container to the pod, with the volumes for the container logs, the configuration and its own position database.\n# logging-mutate-fluentbit-pod-sidecar-v1 is a policy that mutates the pods which have the label # admitik.policy.v1/logging set to true and a configmap with the name in the annotation # admitik.policy.v1/fluentbitConfigmap. # # This policy adds an init container to the pod with the fluentbit sidecar to send the logs to a # fluentd instance. Resources can be customized using the annotation # admitik.policy.v1/fluentbitResources with JSON format. # Example: '{\"limits\":{\"memory\":\"100Mi\"},\"requests\":{\"cpu\":\"100m\",\"memory\":\"50Mi\"}}' apiVersion: admitik.dev/v1alpha1 kind: ClusterMutationPolicy metadata: name: logging-mutate-fluentbit-pod-sidecar-v1 spec: # Resources to be intercepted before reaching the cluster interceptedResources: - group: \"\" version: v1 resource: pods operations: - CREATE # Other resources to be retrieved for conditions templates sources: [] conditions: - name: apply-on-specific-mark engine: cel key: | (has(object.metadata.labels) \u0026\u0026 object.metadata.labels.exists(label, label == 'admitik.policy.v1/logging')) || (has(object.metadata.annotations) \u0026\u0026 object.metadata.annotations.exists(label, label == 'admitik.policy.v1/logging') \u0026\u0026 object.metadata.annotations.exists(label, label == 'admitik.policy.v1/fluentbitConfigmap')) value: \"true\" patch: type: jsonmerge # JsonPatch | JsonMerge engine: starlark template: | def build_patch(): # Default resources default_resources = { \"limits\": { \"memory\": \"50Mi\" }, \"requests\": { \"cpu\": \"50m\", \"memory\": \"50Mi\" } } # Check if custom resources are provided via annotation custom_resources = default_resources if object[\"metadata\"].get(\"annotations\", {}).get(\"admitik.policy.v1/fluentbitResources\"): custom_resources = json.decode(object[\"metadata\"][\"annotations\"][\"admitik.policy.v1/fluentbitResources\"]) # Init containers existing_init_containers = object[\"spec\"].get(\"initContainers\", []) new_container = [ { \"name\": \"fluentbit-sidecar\", \"image\": \"fluent/fluent-bit:4.0.2\", \"restartPolicy\": \"Always\", \"imagePullPolicy\": \"IfNotPresent\", \"command\": [\"/fluent-bit/bin/fluent-bit\"], \"args\": [\"--config=/fluent-bit/etc/fluentbit.conf\"], \"resources\": custom_resources, \"volumeMounts\": [ {\"name\": \"fluentbit-config\", \"mountPath\": \"/fluent-bit/etc/\", \"readOnly\": True}, {\"name\": \"k8s-container-logs\", \"mountPath\": \"/var/log/containers\", \"readOnly\": True}, {\"name\": \"k8s-pods-logs\", \"mountPath\": \"/var/log/pods\", \"readOnly\": True}, {\"name\": \"fluentbit-pos\", \"mountPath\": \"/fluent-bit/pos\"} ], \"securityContext\": { \"runAsNonRoot\": True, \"runAsUser\": 1000, \"allowPrivilegeEscalation\": False, \"capabilities\": { \"drop\": [\"ALL\"] }, \"readOnlyRootFilesystem\": True } } ] # Exclude init container if it already exists existing_container_names = [container[\"name\"] for container in existing_init_containers] if \"fluentbit-sidecar\" not in existing_container_names: init_containers = existing_init_containers + new_container else: init_containers = existing_init_containers # Volumes existing_volumes = object[\"spec\"].get(\"volumes\", []) new_volumes = [ { \"name\": \"fluentbit-config\", \"configMap\": { \"name\": object[\"metadata\"][\"annotations\"][\"admitik.policy.v1/fluentbitConfigmap\"] } }, {\"name\": \"k8s-container-logs\", \"hostPath\": {\"path\": \"/var/log/containers\"}}, {\"name\": \"k8s-pods-logs\", \"hostPath\": {\"path\": \"/var/log/pods\"}}, {\"name\": \"fluentbit-pos\", \"emptyDir\": {}} ] # Exclude volumes if they already exist existing_volume_names = [volume[\"name\"] for volume in existing_volumes] new_volumes_filtered = [volume for volume in new_volumes if volume[\"name\"] not in existing_volume_names] volumes = existing_volumes + new_volumes_filtered return {\"spec\": {\"initContainers\": init_containers, \"volumes\": volumes}} # The result of the template is what the script prints print(json.encode(build_patch())) Notes The sidecar runs as non-root, without privilege escalation, with a read-only root filesystem and every capability dropped. Its resources default to 50m of CPU and 50Mi of memory, and the workload can change them with admitik.policy.v1/loggingSidecarResources. The generation policy also watches rollouts.argoproj.io. Without Argo Rollouts installed that watch retries forever and fills the log of the reflector. Drop it from watchedResources if you do not use it. ","title":"Ship container logs to FluentD without touching the app","url":"/use-cases/centralized-logging-with-fluentbit/"}]