Validate Configuration and Enforce Policies
ConfigHub Triggers enable you to automatically validate configuration data and enforce policies across your Spaces. This guide covers what to check and how: the Validation page, guardrail packs, and writing Triggers of your own. Organize and Troubleshoot Triggers covers running them across an Organization: where to keep them, how Spaces and Targets select them, how their Validation Errors are named, when they run again, and what to do when they don't behave as expected.
For background on the concepts, see:
- Triggers — what Triggers are and how they work
- Functions — the code that Triggers execute
- Gates — how Validation Errors, Validation Warnings, and the Destroy and Delete Gates protect operations
- Working with Functions — how to discover, invoke, and create Triggers
- Organize and Troubleshoot Triggers — sharing Triggers across Spaces and Targets, gate names, re-evaluation and troubleshooting
- Validating backing Unit documents — Triggers on the configuration of ConfigHub's own entities
Day to day, validation and policy checks are managed with two tools built on Triggers: the Validation page in the ConfigHub UI, which shows every check, where its rollout stands and what fails it, and the Kubernetes manager, a cub plugin that installs ready-made guardrail packs and manages their exceptions and enforcement from the command line. Rolling out a check describes using them together, from a new check's first warnings to enforcing it. The rest of this guide covers the Triggers underneath them, for writing checks of your own. To build a tool like the Kubernetes manager for another concern, see building your own manager tool.
The Validation page
Validation in the UI's navigation opens a board of every validating Trigger you can see. It works as a burndown list for rolling out checks: each card counts what still fails its check, and a check moves across the board as its warnings are worked down and it is enforced. The four columns are where each Trigger's enforcement stands:
- Created — no Space or Target selects the Trigger yet, so it checks nothing.
- Audited — selected, and in warn mode: what fails it gets Validation Warnings, which don't block a release.
- Enforced — selected, and blocking: what fails it gets Validation Errors, and isn't released.
- Disabled — the Trigger is disabled.
A Trigger's column is worked out from what selects it and whether it warns, so it moves when one of those changes rather than by dragging its card. Each card shows the Trigger's display name, priority, the date it is due to be enforced, how many Units pass, warn and fail, and how widely it is selected, such as "62 Spaces, 2 Targets". Search by name, slug, description or function, and filter by the Trigger's Pack label, which the Kubernetes manager sets on each of its rules.
Open a card to work on that Trigger:
- Priority and Enforce by set how urgent the check is (High, Medium or Low) and when it is due to be enforced. They are stored as the Trigger's
PriorityandEnforcedByannotations, whichcub manage guardrails status --by-rulereads too. - Audit (warn) and Enforce (block) switch the Trigger between warning and blocking, the same as
--warnand--unwarn, and enforcing records when in itsEnforcedAtannotation. The page says first what the switch will change: what fails the Trigger now is blocked from release, or no longer blocked. - Evaluate runs the Trigger again on the Units it applies to, which is needed after the Trigger or its function changes. It can also run on only the Units you select, or those it has no result for yet.
- The Units it applies to, grouped by Component and then Space, or by Space, show each Unit's result, its Target, and for a failing Unit, the resources it failed on and what was found wrong. Show the failing Units, the passing ones, or those with no result, which say why they have none, such as a Trigger selected after the Unit last changed.
- Exceptions lists the resources excepted from the Trigger, with their reasons, temporary ones first. When the Trigger skips excepted resources, a failing Unit's Except… adds an exception to one of its resources, with a reason and a change description, and an exception can be removed the same way.
- ChangeSets and ChangeOrders opens the changes made to fix what the Trigger found, which are annotated
Trigger=<space>/<trigger>.
The Trigger's controls, from its Controls annotation, are shown with it, and Edit Trigger changes everything else about it.
Guardrail packs with the Kubernetes manager
The Kubernetes manager, cub-manage, manages Kubernetes configuration across a fleet, one concern per command group: namespace, rbac, netpol, workload, scheduling, autoscale and observability. Each group reads the fleet's Units and reports what it finds, fixes it by editing Units rather than clusters, and installs a guardrail pack, a set of validating Triggers that keeps it fixed. It plays the part of a policy library such as the Kyverno policies or Gatekeeper library, checked before release rather than at admission. It is a cub plugin, and uses your cub session:
cub plugin install confighub/cub-manage
cub manage preflight
Every write the tool makes is a dry run that shows the plan until you add --commit, and a commit that changes configuration also needs --change-desc. Its read commands print JSON unless -o table or another -o asks otherwise.
Installing packs
Install the tool-level basic group, whose rules apply to every resource, such as schema validation, unambiguous YAML, no unresolved merge conflicts and no placeholders left on released Units, then the group of each concern you want checked, and any of the packs no group owns: exposure, secrets, metadata and storage.
cub manage guardrails install --commit
cub manage workload guardrails install --commit
cub manage netpol guardrails install --where-space "Labels.Environment = 'prod'" --commit
cub manage guardrails secrets install --commit
Each rule is a Trigger, labeled Pack: <group>, defined once in a policy Space, common unless --policy-space names another. Installing a group adds it to the Trigger selection of each Space in scope, --where-space narrows which, so a Space opts into some groups and not others with one WhereTrigger:
Space.Slug = 'common' AND Labels.Pack IN ('basic', 'workload') AND Labels.AppliedTo != 'Target'
Rules that check only released Units are labeled AppliedTo: Target and selected by Targets instead, narrowed with --where-target. A Space that already selects its Triggers another way is reported and left alone. Installing again updates the rules to the installed version of the tool, and keeps each rule's enforcement and every optional check already installed. --check <name> or --all adds a group's optional checks, --param <check>.<name>=<value> gives a check a parameter, such as the registries allowed-registries allows, and --policy-unit <space>/<unit> installs a rule that runs your own ValidatingAdmissionPolicies from a Unit, so the policies checked before release are the ones your clusters enforce at admission.
Reporting and enforcing rules
Rules install in warn mode, so what fails them gets Validation Warnings, and the Validation page shows them as Audited. Rolling out a check describes working the warnings down and enforcing a rule; these are the commands for each step:
cub manage guardrails status --by-rule -o table
cub manage guardrails update workload-runs-nonroot --priority High --enforced-by 2026-12-31 --commit
cub manage guardrails update workload-runs-nonroot --enforce --commit
status --by-rule reports each rule's stage, priority, due date and how many Units it passes, warns on and blocks, which is what enforcing it would block; status alone lists the Units any Trigger has marked. update --enforce makes the rule block, and --audit makes it warn again. update <rule> --separate <check> moves one check out of a rule into a rule of its own, to enforce it ahead of the rest. The priority, due date and enforcement are the same annotations and warn setting the Validation page shows and changes, so either can be used for any step.
status --framework reports a compliance framework's controls by the checks that correspond to each and how far their rules have got, and lists the controls no check covers: cis-v1.12, cis-eks-v1.8, cis-aks-v1.8, cis-gke-v1.9, nsa, mitre and soc2.
cub manage guardrails status --framework cis-v1.12 -o table
Exceptions to a rule
A resource is excepted from one rule by the annotation exceptions.guardrails.confighub.com/<rule>, whose value says why, as described in exceptions to a check. guardrails exception adds and removes them, and lists every one with its reason; add-temporary excepts everything failing a rule now, as temporary exceptions, so it can be enforced before they are fixed.
cub manage guardrails exception add shop-prod/batch --rule workload-pdb-coverage \
--reason "singleton by design" --commit --change-desc "batch runs one replica"
cub manage guardrails exception list -o table
Intents
An exception excepts a resource from one rule. An intent says what the resource is for, in a word that several rules understand: the annotation intent.guardrails.confighub.com/<intent>. Only its presence counts, and its value records why. A rule can honor an intent in two ways: it skips the resources declaring an intent that trades away the practice it asks for, or it is opt-in, and checks only the resources declaring the intent. Making the intent explicit, rather than leaving it to be inferred from the configuration or recorded as one exception per rule, keeps the decision in one place, and a rule added later that honors the intent applies it without another annotation. The well-known intents are defined by managerkit:
| Intent | What it declares | Rules that honor it |
|---|---|---|
minimize-cost |
The workload trades availability for cost: it deliberately runs as few as one replica, without resource requests or limits, a PodDisruptionBudget or spread across nodes. | replicas, requests, workload-has-limits, workload-pdb-coverage and replicas-spread skip the workload, and autoscale-min-replicas an autoscaler declaring it. |
prometheus |
Prometheus scrapes the resource's metrics. | observability-servicemonitor-coverage checks it, and no other Service. |
guardrails intent declares and removes intents, and lists the resources declaring each, with the rules that honor it. --resource names the resource when the Unit holds more than one, as for exceptions. Declare prometheus on the Service Prometheus scrapes, since that is the resource the coverage rule checks:
cub manage guardrails intent add shop-dev/web --intent minimize-cost \
--reason "dev runs one replica" --commit --change-desc "web trades availability for cost in dev"
cub manage guardrails intent add shop-prod/web --resource v1/Service/shop/web --intent prometheus \
--commit --change-desc "Prometheus scrapes web"
cub manage guardrails intent list -o table
cub manage guardrails intent --help lists the well-known intents and the installed tool's rules that honor each. Like an exception, an intent is a change to the Unit, and is released with it. On the Validation page, a rule's Exceptions also lists the resources it skips by intent.
The tool's README and cub manage <group> --help describe each group's reports and fixes, and its design describes each group and its rules.
Rolling out a check
A new check finds problems in configuration that is already running, so it starts in warn mode, and is enforced only once what it finds has been dealt with. Then it blocks the next resource that fails it, so the problem doesn't come back. Work through the checks one Trigger at a time:
- Prioritize the warnings. The Validation page is the burndown list for this work. Give each Trigger a priority and the date it is due to be enforced, with Priority and Enforce by on the Validation page, or
cub manage guardrails update <rule> --priority High --enforced-by 2026-12-31 --commitfor a guardrail rule. The board lists the Audited Triggers by priority, then by due date, then by how many Units fail them. - Review the findings. Open the Trigger's card. Its failing Units are grouped by Component and Space, each with the resources it failed on and what was found wrong, and a Unit's own page shows the paths and values. Problems that repeat across a Component's variants often come from its base.
-
Fix what can be fixed, in a ChangeSet and a ChangeOrder. Make the fix in the Space the value comes from, usually the Component's base, in a ChangeSet, so it can be reviewed and reverted as one change, then carry it to the variants with a ChangeOrder and release it. Annotate both
Trigger=<space>/<trigger>, naming the Trigger in the policy Space, and the Trigger's ChangeSets and ChangeOrders on the Validation page lists them. This is a good task for an AI agent withcub: give it the Trigger and its findings, and ask for the fix as a ChangeSet and a ChangeOrder. The commands look like this:cub changeset create --space shop-base runs-nonroot --description "Run the shop workloads as non-root, for workload-runs-nonroot" --annotation Trigger=common/workload-runs-nonroot cub variant changeset open shop-base runs-nonroot --where "Slug = 'checkout'" cub manage workload harden shop-base/checkout --changeset shop-base/runs-nonroot --commit --change-desc "Run checkout as non-root" cub variant changeset close shop-base runs-nonroot cub changeorder create --space shop-base runs-nonroot --description "Run the shop workloads as non-root, for workload-runs-nonroot" --annotation Trigger=common/workload-runs-nonroot --end-tag shop-base/runs-nonroot-endThen promote the ChangeOrder and publish each Space's Release, as in tracking and promoting changes. From the Validation page, selecting failing Units and choosing Run a function… runs a function on them in a ChangeSet of the Trigger's, named after it and left open for review. 4. Except what is meant to break the check. A resource that has to fail it, such as a singleton that can't have a PodDisruptionBudget, gets an exception with a reason: Except… on its Unit on the Validation page, or
cub manage guardrails exception add. When the reason is what the resource is for, such as a workload run at the least cost, declare an intent instead, which every rule honoring it applies. Where fixes will take longer than the check should wait, temporary exceptions let it be enforced now. 5. Enforce it. Once nothing is left failing, choose Enforce (block), or runcub manage guardrails update <rule> --enforce --commit. What fails the Trigger from then on gets Validation Errors, and isn't released until it is fixed or excepted.
Building your own manager tool
The Kubernetes manager is built on managerkit, a module of the ConfigHub SDK (github.com/confighub/sdk/managerkit) that holds the parts every manager tool shares, so a tool for another concern, or one that extends the Kubernetes manager with rules of its own, has the same commands, flags and output. Its packages are:
guardrails— a tool's policy pack: aPackofChecks, each a CEL expression run byvet-cel, a Pod Security Standards check, a ValidatingAdmissionPolicy from a library, or another validating function, with a control number, priority and the resource types it governs. A check'sExceptIntentsname the intents that except a resource from it, and itsOptInIntentmakes it check only the resources declaring that intent, from the well-known intents the package defines (WellKnownIntents). It provides theguardrails install,status(with--framework),update,exceptionandintentcommands described above, and installs each rule as a Trigger in the shared policy Space, so its rules appear on the Validation page beside the Kubernetes manager's.profiles— a library of named, reusable edits stored as Invocations, withprofile install,profile list,profile apply, andfleet-edit --profileto apply one to every Unit a filter selects.write— how a mutating command reports what it changed, Unit by Unit, as a dry run or after a commit.configmaps— the Triggers that roll a workload when a ConfigMap it uses changes, and prune the immutable ConfigMaps a rendering leaves behind.
Reading the fleet is in the SDK's cubapi package, and the shared --where and Space-label flags in cliutil. The managerkit README has an example of a tool declaring a pack and a profile library.
Creating Triggers
A Trigger associates a Function with an Event type (e.g., Mutation, PostClone) and a configuration format (ToolchainType). When the specified event occurs on a Unit, the function is automatically invoked.
cub trigger create --space my-space check-replicas Mutation Kubernetes/YAML vet-celexpr 'r.kind != "Deployment" || r.spec.replicas > 1'
Description
Use --description to explain what the Trigger checks and how to fix failures. The description is shown in the UI on the Trigger's card in a unit's Overview tab, beside what the Trigger found, and when hovering over a Validation Error.
cub trigger create --space my-space check-replicas Mutation Kubernetes/YAML \
--description "Ensures Deployments have more than one replica for high availability" \
vet-celexpr 'r.kind != "Deployment" || r.spec.replicas > 1'
When no description is provided, the UI shows the function name and arguments as a fallback.
Warn mode
Use --warn to create a non-blocking Trigger that produces Validation Warnings instead of Validation Errors. This is useful for advisory policies or gradual rollouts:
cub trigger create --space my-space soft-check Mutation Kubernetes/YAML --warn vet-celexpr '...'
Toggle warn mode on an existing Trigger with --warn or --unwarn on update.
Guarding what a mutating Trigger writes
--guard Trigger=<slug> on a mutating Trigger, with --clearance Trigger=<slug> so that its own next run may write the paths again, records a guard naming the Trigger on the paths its function writes. A later merge from upstream does not overwrite them, and a hand edit to them is withheld unless it passes --clearance Trigger=<slug>, since the Trigger would write its value back the next time it runs. Use it for a Trigger that decides a value the variant then owns, such as a PostClone Trigger that sets a variant's namespace or replica count. Leave it off a Trigger that applies an organization-wide default, whose value should follow upstream changes like any other. Deleting the Trigger removes the guards it recorded, and updating it removes those it no longer states. --protect, which earlier releases used for this, is deprecated and sets the same guard and clearance.
Filtering which Units a Trigger applies to
By default, a Trigger applies to all Units in the Space (and any Spaces or Targets that select it). You can restrict which Units a Trigger applies to using:
-
--where-unit-field— a filter expression evaluated against Unit metadata, which sets the Trigger'sWhereUnit:cub trigger create --space my-space check-prod Mutation Kubernetes/YAML \ --where-unit-field "Labels.Environment = 'production'" \ vet-celexpr '...' -
--unit-filter— a reference to a saved Filter entity withFrom=Unit:cub filter create --space my-space prod-units Unit --where-field "Labels.Environment = 'production'" cub trigger create --space my-space check-prod Mutation Kubernetes/YAML \ --unit-filter my-space/prod-units \ vet-celexpr '...' -
--where-resource— restricts which resources within a Unit's configuration data the function operates on, using metadata path expressions. See Exceptions to a check for using it to skip excepted resources.
Exceptions to a check
Some resources are meant to break a rule, such as an operator's ClusterRole that needs wildcard permissions. Rather than weakening the rule, mark each such resource with an annotation naming the check, whose value says why, and have the Trigger skip the resources that carry it:
cub trigger create --space my-space no-rbac-wildcards Mutation Kubernetes/YAML \
--where-resource "metadata.annotations.exceptions~1example~1com/no-rbac-wildcards IS NULL" \
vet-celexpr '...'
The Trigger checks every resource without the annotation, and other Triggers still check the excepted ones. ~1 writes the dots inside the annotation key, so that they aren't read as path separators. Add the annotation to one resource of a Unit with set-annotation and a --where-resource naming that resource. A cluster-scoped resource's name starts with /:
cub function set --space my-space --where "Slug = 'argocd'" \
--where-resource "ConfigHub.ResourceName = '/argocd-application-controller'" \
-- set-annotation exceptions.example.com/no-rbac-wildcards "argocd manages every resource type"
The Validation page lists the resources excepted from a Trigger with their reasons, and a Unit's Overview lists its own exceptions below its Validation Errors and Warnings.
An annotation can also state a reason that several Triggers honor, rather than naming one check. Each Trigger that a workload run for minimum cost should not apply to, for example, skips the resources declaring it, with another clause in its --where-resource:
--where-resource "metadata.annotations.exceptions~1example~1com/requests IS NULL AND metadata.annotations.intent~1example~1com/minimize-cost IS NULL"
IS NOT NULL makes a Trigger opt-in instead: it checks only the resources that carry the annotation. A where expression has no OR, so a Trigger can be opted into by one annotation. The Kubernetes manager writes its rules this way, with the intent.guardrails.confighub.com/ annotations.
Temporary exceptions
To enforce a check before everything that fails it today is fixed, except each failing resource with a reason that starts with ToBeFixed, such as ToBeFixed: images are rebuilt next quarter. The Trigger then blocks only new failures, and the prefix marks the exception as one still to be fixed. The Validation page and the Unit page list these as Temporary Exceptions, apart from the exceptions that are meant to stay.
On the Validation page, open the Trigger and choose Except the failing Units temporarily…, or select some of its Units and choose Except temporarily…. Each failing Unit gets the annotation on the resources the Trigger's results name, or on its only resource when the results name none. A Unit whose failing resource can't be identified is listed and left as it is: for example, one holding a Deployment and a Service with the same name, when the results give only the name. Like any exception, the annotation is a change to the Unit. Then enforce the Trigger, with Enforce (block) on the Validation page or --unwarn, and remove each temporary exception once its resource is fixed.
With the Kubernetes manager's guardrail packs, cub manage guardrails exception add-temporary --rule <rule> --reason "<why>" does the same from the command line, as a dry run unless you add --commit --change-desc "<description>". cub manage guardrails exception list --temporary lists the temporary exceptions that are left.
Triggers on a Channel
A Trigger can run an external function, served by a function bot on a Channel, instead of a built-in one:
cub trigger create --space my-space policy-check Mutation Kubernetes/YAML \
--channel my-space/policy-bot \
vet-my-policy
See when a Channel's bot is unavailable for how ConfigHub handles a bot that is not running.
Recommended validation and policy functions
Preventing mistakes with built-in validation
These built-in functions catch common errors and are recommended as Triggers for all Spaces:
vet-schemas — runs kubeconform to validate Kubernetes resource schemas. This catches typos in field names, incorrect types, missing required fields, and invalid API versions before configuration is released:
cub trigger create --space my-space valid-k8s Mutation Kubernetes/YAML vet-schemas
vet-placeholders — detects placeholder values that have not yet been replaced by the user or resolved through a linked configuration. Placeholder values (such as confighubplaceholder or 999999999) indicate that a value still needs to be provided. This prevents deploying incomplete configuration:
cub trigger create --space my-space complete-k8s Mutation Kubernetes/YAML vet-placeholders
Beyond those two, these are worth running everywhere:
vet-formatrejects YAML that parses differently from how it reads, or not at all in some tools: anchors and aliases, duplicate keys, values such asyesandonthat YAML 1.1 reads as booleans, and old-style octals.vet-merge-keysfails when a list holds two entries with the same strategic-merge key, such as two containers or two environment variables with the same name, which Kubernetes refuses to apply.vet-immutablefails when a change modifies a field Kubernetes does not allow to change after an object is created, such as a Deployment's selector, compared with the revision last released. A Trigger passes that revision to it without being told.vet-no-merge-conflictsfails while a Unit has conflicts a merge could not apply, so a Space that promotions merge into does not release a Unit that silently missed part of a change.
Custom policy expressions with CEL
vet-celexpr — evaluates a simple boolean CEL expression against each resource. The resource is available as r. Returns true (pass) or false (fail). Use this for straightforward constraints:
cub trigger create --space my-space check-replicas Mutation Kubernetes/YAML \
vet-celexpr 'r.kind != "Deployment" || r.spec.replicas > 1'
A more realistic example enforcing that Deployments run as non-root:
cub trigger create --space my-space ensure-nonroot Mutation Kubernetes/YAML \
--description "Ensures Deployment containers run as non-root" \
vet-celexpr 'r.kind != "Deployment" || (r.spec.template.spec.securityContext.runAsNonRoot == true && r.spec.template.spec.containers.all(container, !has(container.securityContext.runAsNonRoot) || container.securityContext.runAsNonRoot == true)) || r.spec.template.spec.containers.all(container, has(container.securityContext.runAsNonRoot) && container.securityContext.runAsNonRoot == true)'
vet-cel — a more capable CEL function that can return a ValidationResult with detailed failure information. The expression can return a simple bool, or a map with passed (bool) and details (list of strings):
cub trigger create --space my-space check-labels Mutation Kubernetes/YAML \
vet-cel 'has(r.metadata.labels) && has(r.metadata.labels.team) ? {"passed": true} : {"passed": false, "details": ["Missing required label: team"]}'
Parameters follow the expression as key=value arguments, and the expression reads them as strings from params, so the same expression can be stored once with different values:
cub trigger create --space my-space min-replicas Mutation Kubernetes/YAML \
-- vet-cel 'r.kind != "Deployment" || r.spec.replicas >= int(params.min)' min=2
In the named form, each one is a --param=key=value after --expression='...'. A --param key=value with a space is read as two arguments, and refused.
The map can also name the fields that failed, in failed_attributes: a list of maps with ResourceType, ResourceName, and Path, and optionally Value. cub unit blame then marks those fields, and cub unit path shows the check and its details on each:
cub trigger create --space my-space check-replicas Mutation Kubernetes/YAML \
vet-cel 'r.kind != "Deployment" || r.spec.replicas > 1 ? {"passed": true} : {"passed": false, "details": ["replicas must be more than 1"], "failed_attributes": [{"ResourceType": r.apiVersion + "/" + r.kind, "ResourceName": r.metadata.namespace + "/" + r.metadata.name, "Path": "spec.replicas"}]}'
Custom policy logic with Starlark
vet-starlark — validates resources using a Starlark program (a Python-like language created by Google). The program must define a validate(r) function that returns a dict with passed (bool) and optionally details (list of strings). Starlark is a good choice for policies that involve more complex logic than a single CEL expression can express:
cub trigger create --space my-space check-resources Mutation Kubernetes/YAML \
vet-starlark 'def validate(r):
if r["kind"] != "Deployment":
return {"passed": True}
containers = r["spec"]["template"]["spec"]["containers"]
missing = [c["name"] for c in containers if "resources" not in c or "requests" not in c.get("resources", {})]
if missing:
return {"passed": False, "details": ["Containers missing resource requests: " + ", ".join(missing)]}
return {"passed": True}'
Policy engines: Kyverno and OPA Gatekeeper
For organizations that already use Kyverno or OPA Gatekeeper to enforce policies at Kubernetes admission time, ConfigHub can validate configuration against the same policies before deployment. This gives you a single set of policies for both admission control and pre-deployment validation.
The validation runs as an external function in a function bot you deploy next to the policy engine. The examples repo has ready-to-build bots for:
- admission-webhook — validates against Kyverno policies or OPA Gatekeeper constraints through their webhook servers, with its
vet-kyverno-serverandvet-opa-gatekeeperfunctions - kyverno — validates using Kyverno as a library (no running server needed)
- kube-score — scores Kubernetes resources against best-practice checks
Once the bot holds its Channel, create a Trigger to validate configuration automatically:
cub trigger create --space my-space validate-kyverno Mutation Kubernetes/YAML \
--channel my-space/admission-bot \
vet-kyverno-server
For details on deploying the webhook validation bot, see the admission webhook functions guide. For background on Kubernetes policy enforcement, see What are state-based policy constraints good for? and Vetting Kubernetes configuration with Kyverno prior to deployment.
Checks that read other Units
A validating function checks one Unit at a time, but many rules are about more than one resource: whether any NetworkPolicy selects a Deployment, whether a PodDisruptionBudget covers it, whether the ServiceAccount its pods name exists, whether two Ingresses claim the same host. Kubernetes admission has the same limit, since a webhook is sent only the object being admitted, and policy engines work around it by reading the cluster: Gatekeeper replicates objects into data.inventory for its referential constraints, and Kyverno looks them up with API calls. A Trigger instead names or selects the other Units its function reads, and ConfigHub passes their configuration to the function as OtherData, so the check runs on configuration before it is released, and again whenever either side changes. The Kubernetes manager's guardrail packs check NetworkPolicy, PodDisruptionBudget and ServiceMonitor coverage this way, among others.
Naming other Units
--other-unit key=unit passes one Unit to the Trigger's function under a key, the name the function reads it by. Use it for configuration that is the same wherever the Trigger runs, such as a Unit of ValidatingAdmissionPolicies, which vet-validating-admission-policy reads under policy. Naming a Unit requires Use permission on it, and a Unit a Trigger names cannot be deleted until the Trigger stops naming it. A Trigger that runs an Invocation passes the Units the Invocation names instead.
Selecting other Units
Most such rules are about what else is on the same cluster, and which Units those are depends on where the Unit being checked is released. --other-unit-selection-where key=expression selects the Units to pass under a key rather than naming them: each Space that selects the Trigger evaluates the expression for itself, as a Unit filter in which EvaluatingSpace stands for that Space. This Trigger warns on a Deployment or StatefulSet that no NetworkPolicy on its cluster selects:
cub trigger create --space platform-policies netpol-coverage Mutation Kubernetes/YAML \
--description "Each workload has a NetworkPolicy isolating its ingress" \
--where-resource "ConfigHub.ResourceType IN ('apps/v1/Deployment', 'apps/v1/StatefulSet')" \
--other-unit-selection-where "policies=Space.ReleaseTargetID = EvaluatingSpace.ReleaseTargetID" \
--other-unit-selection-where-resource "policies=ConfigHub.ResourceType = 'networking.k8s.io/v1/NetworkPolicy'" \
--warn \
vet-cel 'other.?policies.orValue([]).exists(p, p.metadata.namespace == r.metadata.namespace && selects(p.spec.podSelector, podLabels(r))) ? {"passed": true} : {"passed": false, "details": ["no NetworkPolicy selects " + r.metadata.name]}'
A selection has up to three parts, which all apply:
--other-unit-selection-where key=expression— the Units, by their own fields and labels and those of their Space, such asSpace.ReleaseTargetID = EvaluatingSpace.ReleaseTargetIDfor the Units released to the same Target, orSpace.Labels.Environment = EvaluatingSpace.Labels.Environment.--other-unit-selection-filter key=filter— a saved Filter of Units (From=Unit) the Units must also match.--other-unit-selection-where-resource key=expression— the Units holding a resource the expression matches, such asConfigHub.ResourceType = 'networking.k8s.io/v1/NetworkPolicy', and only those resources are passed. The function reads the NetworkPolicies on the cluster, not every resource of the Units that hold them.
A selection needs at least one of them, and picks only Units of the Trigger's ToolchainType. It picks however many Units match, none included, and the function runs with whatever was picked, so the function decides what an empty selection means. A Space with no release Target has no ReleaseTargetID, which compares equal to nothing, so a selection like the one above passes it nothing; the guardrails of the Kubernetes manager pass such a Unit, by checking functionContext.TargetID. The resources the selection's WhereResource matches in the Unit being checked are passed too, first, so a check sees a NetworkPolicy in the same Unit as the workload.
The Space records the Units each selection picked, by Trigger and key, and cub space get shows how many each one picked:
Other Units netpol-coverage/policies 1 units
A Space evaluates its selections when it evaluates which Triggers it selects: when it is created, when its WhereTrigger or TriggerFilterID changes, and when its Trigger list is refreshed with cub space update --patch --refresh-triggers. Whoever makes that change needs Use permission on each Unit a selection adds; the Units already recorded are kept whoever refreshes. A Trigger that a Target selects, rather than a Space, is passed nothing under its selections for now; we plan to have Targets record their selections too.
Reading other Units in a function
vet-cel and vet-starlark pass the other Units as other, a map from each key to the list of resources passed under it, and where each came from as otherOrigins, a list at the same positions of the UnitSlug, SpaceSlug, UnitID, SpaceID, RevisionNum and UnitLabels it came from. In CEL, read a key with other.?policies.orValue([]), since a key with nothing passed under it may be absent. Three functions match selectors the way Kubernetes does:
selects(selector, labels)— whether a label selector, withmatchLabelsandmatchExpressions, selects the labels, as the API server reads one: an empty selector selects everything, and a null one nothing.podLabels(resource)— the labels of the pods a resource runs, wherever its kind keeps them, such as a CronJob'sspec.jobTemplate.spec.template.metadata.labels; null for a kind that runs no pods.namespaceLabels(namespaces, name)— the labels of the named Namespace among the resources passed, including thekubernetes.io/metadata.namelabel the API server sets, to match anamespaceSelector.
Other functions read particular keys: vet-validating-admission-policy reads its policies under policy and their parameters under params, and vet-pod-security-standard with level=namespace reads each workload's Namespace under namespaces when it is not in the Unit being checked.
When the other Units change
A change to the configuration of a Unit a Trigger names, or that a Space recorded for one of its selections, runs the Trigger again on the Units it applies to in each Space that reads the changed Unit. Fixing a NetworkPolicy clears the warning on the workload without a change to the workload's Unit. Deleting a selected Unit removes it from the Spaces' records and runs the Trigger again the same way. Which Units a selection picks changes only when a Space evaluates it: a Unit added to the cluster is read once the Spaces that should read it are refreshed.
Finding what a selector selects
To see what a check is matching, cub resource list finds the resources a selector selects, and those whose selectors select a workload's pods. --selected-by names a NetworkPolicy, PodDisruptionBudget or Service and lists the workloads whose pods its selector selects; --selecting names a workload and lists the NetworkPolicies, PodDisruptionBudgets and Services that select its pods. Both match as Kubernetes does, in the named resource's namespace and on its cluster: among the resources released to its Target, or in its Space when it has none. Each takes a ResourceID, or the resource as cub resource list -o name prints it:
cub resource list --selecting my-app/workloads:apps/v1/Deployment/shop/web
cub resource list --selected-by platform/netpols:networking.k8s.io/v1/NetworkPolicy/shop/web-ingress
SPACE UNIT TARGET TYPE NAME
platform netpols cluster-a networking.k8s.io/v1/NetworkPolicy shop/web-ingress
platform platform cluster-a policy/v1/PodDisruptionBudget shop/web
In the UI, a Trigger's add and edit drawers have an Other Data section for the Units it names and its selections, the Trigger lists can show both as columns, and the Resource explorer offers the same search from a resource's panel.
Related reading
- Organize and Troubleshoot Triggers, for sharing Triggers across Spaces and Targets, and for Triggers that don't run or fail unexpectedly
- Review and Approve Changes, for approvals, which a ChangeWorkflow requires rather than a Trigger
- Validate with Admission Webhooks, for Kyverno and OPA Gatekeeper policies