Get the Zoom link
Cloud Security Office Hours Banner

CEL policy expressions, hands-on

CEL (Common Expression Language) is a small language for single-expression rules such as "every container must set a memory limit". It is small on purpose: no loops, no way to change anything, and every expression is guaranteed to finish. That is why Kubernetes and Google Cloud IAM run it inside their own servers, and why it is now the default way to write admission policy, the rules Kubernetes checks before it accepts a change.

Jump to the walk-through All how-to guides

·

Time: ~2 hours  ·  Difficulty: Intermediate  ·  You need: Python 3.10 or later for the expression lab; Docker and kind if you want to run the admission policy for real; a Google Cloud organization, and the right to change its policies, if you want to enforce the custom constraint

How this page was checked: a script extracted every code block on this page and ran it on 4 November 2026 on an Apple silicon Mac, and the outputs shown are pasted from that run; a planted error in a block made the script fail, so the check can fail. The CEL ran in cel-python 0.5.0 on Python 3.10, the expression lab's shell blocks in a clean interactive zsh, and exercise 4's Rego in OPA 1.22.0, with a package line added. The kind lines in step 5 ran on kind 0.33.0 (Kubernetes 1.37.0) and printed the refusal shown. Every Kubernetes object, including the exercise answers, was applied to a local Kubernetes 1.37.0 API server (the kube-apiserver and etcd binaries the Kubernetes project publishes for envtest), with the CRD schema and the bare validations lists wrapped in the smallest complete object that holds them. The IAM condition in step 6 was evaluated by cel-python with test values, not by IAM. For the Google Cloud section, no constraint or organization policy was created and none of its gcloud commands was run, since each is an organization-level change: the files were parsed with the Google Cloud SDK 585.0.0's own readers, the commands were checked against its help, the conditions were evaluated locally against JSON shaped like the Cloud Storage API's bucket resource, and what Google's evaluator does with them comes from Google's documentation as of 4 November 2026.

Slides: download the PDF or make your own editable copy (copying needs a Google account). The slides are licensed CC BY-NC 4.0.

The policy language that lives inside the thing it governs

Kubernetes and Google Cloud both let you write rules that a new or changed resource must pass before it is accepted: every container must set a memory limit, every storage bucket must block public access. Platform and security teams write many of those rules in Common Expression Language (CEL), each as a single expression that comes out true or false.

CEL is deliberately small. It is not Turing complete, which means it cannot express every program a general-purpose language can; it has no side effects, so evaluating an expression never changes anything; and every expression is guaranteed to terminate. Those three properties sound like limitations, and they are exactly why CEL is everywhere: if evaluation cannot loop forever and cannot reach out to the network, it is safe to run inside a hot path, the code that every request passes through.

So CEL runs where a general-purpose policy engine cannot. It is embedded in the Kubernetes API server itself, the part of Kubernetes that receives every request to create or change something in a cluster. It is also in Google Cloud IAM's condition evaluator and Google Cloud's custom organization policy constraints, in Envoy, in Firebase security rules, and in CRD field validation, the checks on the new resource types that a CustomResourceDefinition (CRD) adds to a cluster. There is no sidecar (a helper container running beside the application), no webhook (a call out to a separate service), no extra network hop, and nothing to be unavailable at the moment a decision is needed.

That is the real contrast with OPA and Rego, and it is worth having a clear view of it because the two are increasingly presented as alternatives. Rego is a full policy language evaluated by a separate engine. It can join across documents, load external data, and express arbitrarily complex logic, and it costs you a component to deploy, secure, and keep available. CEL is an expression evaluated in-process by the host, the program that is already handling the request. It cannot do joins or fetch data. It also cannot be down, cannot add latency you did not already have, and cannot be bypassed by a network failure.

For "no privileged containers in this namespace", CEL is straightforwardly the better answer now that it is built in. For "no image outside our registry unless the team owns a documented exception recorded in this other system", it is the wrong tool and no amount of cleverness fixes that.

Learning CEL is two separate jobs, and only one of them is the language. The syntax is small enough to learn in an afternoon. The other job, which is where the actual time goes, is learning what variables each host hands you. Kubernetes admission gives you object, oldObject, request, params, authorizer, namespaceObject, and variables. GCP IAM gives you request.time, resource.name, resource.type, and friends. A Google Cloud custom constraint gives you resource, the REST representation of the thing being created or updated. Same language, entirely different vocabulary.

On this page

  1. How to use this guide
  2. What a CEL policy is made of
  3. Walk-through
  4. Google Cloud custom organization policy constraints
  5. Hands-on exercises
  6. Common mistakes
  7. Where next

How to use this guide

This guide is marked intermediate. It assumes you know Kubernetes basics: that a Pod is one or more containers run together, what Deployments and namespaces are, that YAML manifests describe them, and that kubectl apply sends a manifest to a cluster. The site's Kubernetes security guide explains Pods and namespaces, and its section on admission control shows where these policies run. The Google Cloud section also assumes you know that Google Cloud groups projects into folders under an organization, which the Google Cloud security guide lays out. CEL itself is taught from the start, and the lab needs Python installed but no Python knowledge.

Read the next section first: it shows what a CEL policy is made of, and its examples are there to read. The walk-through then works in a lab folder on your computer. Step 1 saves a sample Pod as pod.json and writes cel.py, a few lines of Python that evaluate each expression you give them against that sample; steps 2 and 3 run expressions through it. Steps 4 and 5 write a real Kubernetes admission policy and, if you have Docker and kind, try it on a throwaway cluster. Step 6 shows two other places the same expressions turn up, and step 7 shows a policy asking the cluster's own access-control rules a question. The Google Cloud section after the walk-through applies CEL to Google Cloud's custom constraints and reuses cel.py. The exercises run in the same lab, with each answer hidden until you open Show the answer.

Each input block has a label at the top, and every block has a copy button. A block labelled BASH holds commands to paste into your terminal. Several of them contain a line such as cat > pod.json <<'EOF', which writes every line down to the one that says only EOF into a file called pod.json; paste the whole block at once, the EOF line included. A block labelled YAML is a Kubernetes or Google Cloud object, or part of one: save it only when the text says to, as step 5 does with step 4's policy. Blocks labelled CEL hold expressions to read, and the one labelled REGO belongs to exercise 4. An unlabelled block is output: what the command before it should print.

Where the page shows output, yours should match it. A script ran the page's code blocks on 4 November 2026, with cel-python 0.5.0 on Python 3.10 and, for step 5, kind 0.33.0, and the outputs shown are pasted from that run. Steps 1 to 3 do not show their output; step 3 says which results to look for. Two parts were not run the way you would run them. The Google Cloud IAM condition in step 6 was evaluated by cel-python with test values, not by IAM. None of the gcloud commands in the Google Cloud section was run, because each changes an organization's policies: they were checked against the Google Cloud SDK's help, and what Google does with a condition comes from Google's documentation.

If you work only in Kubernetes, the Google Cloud section can wait for a second reading, though exercise 5 uses it. If you work only in Google Cloud, read the next section and steps 1 to 3, skim step 4's policy and binding, which the Google Cloud section compares its own two objects to, then go to the Google Cloud section. If an expression gives a result the page does not lead you to expect, check that you are in ~/cel-lab, where step 1 saved pod.json and cel.py; that DOC names the file you meant, since cel.py reads pod.json unless it does; and that your cel-python is the 0.5.0 the page used, since pip3 install fetches the newest release.

What a CEL policy is made of

Say a cluster should refuse any Pod with a container that might run as root. In CEL that whole rule is one expression that comes out true for an acceptable Pod and false for any other, and the obvious first version breaks on a container that leaves out its security settings. This section covers what such an expression is built from, and why that version breaks. An expression reads variables that its host supplies: in Kubernetes admission, object is the resource being checked. CEL's name for that set of variables is the activation, and the highlighted box above the contents list says what three of those hosts provide.

A CEL policy is one expression that evaluates to a boolean. There is no statement sequence, no assignment, no early return, and no function you define yourself. If you are reaching for those, you have hit the ceiling and should be looking at a different layer.

Iteration exists, but only through macros, and only bounded by a collection you already have:

That last one is the thing to internalise first. Reading a field that is not there is an error in CEL, not a false and not a null. An error propagates and the whole expression fails, which in Kubernetes admission means the policy's failurePolicy, the setting that says whether an error blocks the request or lets it through, decides your fate (step 4 sets it). has() before you dereference an optional field is not defensive style, it is the difference between a working policy and one that fails open or blocks every deployment.

// Errors, if any container omits securityContext:
object.spec.containers.all(c, c.securityContext.runAsNonRoot == true)

// Correct: presence-check first. && short-circuits, so the right-hand
// side is never evaluated when has() is false.
object.spec.containers.all(c,
  has(c.securityContext) && c.securityContext.runAsNonRoot == true)

Step 3 runs the macros against a sample Pod, step 7 meets the has() lesson again inside a real policy, and the Google Cloud section shows a host where missing fields behave differently.

Walk-through

1. Get an evaluator you can iterate in

Writing CEL by pushing YAML at a cluster and reading admission errors is a miserable loop. Evaluate expressions locally first, with cel-python, an implementation of CEL written in Python.

mkdir -p ~/cel-lab && cd ~/cel-lab
pip3 install cel-python==0.5.0

cat > pod.json <<'EOF'
{"object": {"metadata": {"name": "web", "labels": {"team": "payments"}},
 "spec": {"replicas": 7,
   "containers": [
     {"name": "app", "image": "ghcr.io/acme/app:1.2.3",
      "securityContext": {"runAsNonRoot": true, "privileged": false},
      "resources": {"limits": {"cpu": "500m", "memory": "512Mi"}}},
     {"name": "sidecar", "image": "docker.io/library/busybox:latest"}
   ]}}}
EOF

cat > cel.py <<'EOF'
import os, sys, json, celpy
env = celpy.Environment()
doc = celpy.json_to_cel(json.load(open(os.environ.get('DOC', 'pod.json'))))
for src in sys.argv[1:]:
    print(f"{src}\n  -> {env.program(env.compile(src)).evaluate(doc)}\n")
EOF

python3 cel.py 'object.spec.replicas <= 5'

2. The syntax, in one pass

python3 cel.py \
  'object.metadata.name == "web"' \
  'object.spec.replicas > 5 && object.spec.replicas < 20' \
  '"team" in object.metadata.labels' \
  'object.metadata.labels["team"] == "payments"' \
  'object.metadata.name.startsWith("web")' \
  'size(object.spec.containers) == 2' \
  'object.spec.replicas > 5 ? "too many" : "ok"'

C-like, and mostly unsurprising. Strings are double-quoted or single-quoted, in tests map keys and list membership, and there is a ternary, a ? b : c, which gives b when a is true and c otherwise. The standard library gives you startsWith, endsWith, contains, matches (a regular expression, RE2 flavoured, so no lookaround), size, and duration and timestamp arithmetic.

3. Macros, which is where real policies live

python3 cel.py \
  'object.spec.containers.all(c, has(c.resources) && has(c.resources.limits))' \
  'object.spec.containers.exists(c, c.image.endsWith(":latest"))' \
  'object.spec.containers.map(c, c.name)' \
  'size(object.spec.containers.filter(c, !has(c.securityContext)))' \
  'object.spec.containers.all(c, c.image.startsWith("ghcr.io/acme/"))'

Run these against the sample and read the results carefully. The sidecar container has no securityContext and no resources, and pulls :latest from Docker Hub, so both all() checks print False, the exists() check for :latest prints True, and the count of containers with no securityContext is 1. That is a deliberately realistic shape: the workload people wrote carefully, plus the container somebody added in a hurry.

4. Write a real ValidatingAdmissionPolicy

This is native Kubernetes admission control (the API server's checks on a request to create, change or delete an object, made after it has confirmed who is asking and that they may), generally available since Kubernetes 1.30. No webhook, no controller, no certificate rotation.

apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
  name: "require-resource-limits.csoh.org"
spec:
  # Fail = an error evaluating the policy denies the request.
  # Ignore = an error lets it through. Choose deliberately.
  failurePolicy: Fail

  # Coarse filter: which API objects this policy is even considered for.
  matchConstraints:
    resourceRules:
      - apiGroups:   ["apps"]
        apiVersions: ["v1"]
        operations:  ["CREATE", "UPDATE"]
        resources:   ["deployments"]

  validations:
    - expression: >-
        object.spec.template.spec.containers.all(c,
          has(c.resources) && has(c.resources.limits) &&
          has(c.resources.limits.memory))
      message: "every container must set a memory limit"

    - expression: >-
        object.spec.template.spec.containers.all(c,
          !c.image.endsWith(":latest"))
      message: "image tags must be pinned; :latest is not a version"

The policy on its own does nothing. It needs a binding, and the separation is the good part: one policy, several bindings, each scoped differently and each choosing its own enforcement strength.

apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
  name: "require-resource-limits-prod.csoh.org"
spec:
  policyName: "require-resource-limits.csoh.org"
  # Deny | Warn | Audit. Audit combines with either; Deny and Warn cannot be combined.
  validationActions: [Deny]
  matchResources:
    namespaceSelector:
      matchLabels:
        environment: production
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
  name: "require-resource-limits-dev.csoh.org"
spec:
  policyName: "require-resource-limits.csoh.org"
  validationActions: [Warn, Audit]   # same rule, observe-only in dev
  matchResources:
    namespaceSelector:
      matchLabels:
        environment: development

That two-binding pattern is how you roll a policy out without an outage. Bind it as [Warn, Audit] everywhere first, read the audit log for a week to find out what it would have blocked, and only then add a Deny binding scoped to the namespaces you have cleaned up.

5. Try it on a throwaway cluster

Save the policy and both bindings from step 4 in one file, policy.yaml, with a --- line between the policy and the first binding. Any recent Kubernetes will do, since ValidatingAdmissionPolicy is GA from 1.30.

kind create cluster --name cel-lab
kubectl apply -f policy.yaml

kubectl create namespace prod
kubectl label namespace prod environment=production

kubectl -n prod create deployment bad --image=nginx:latest

kind delete cluster --name cel-lab

The create deployment line should be refused with the message of the first validation it fails:

error: failed to create deployment: deployments.apps "bad" is forbidden: ValidatingAdmissionPolicy 'require-resource-limits.csoh.org' with binding 'require-resource-limits-prod.csoh.org' denied request: every container must set a memory limit

6. Two other places the same expressions turn up

CRD field validation. The same CEL, attached to a schema, so an invalid custom resource is rejected on write with no controller involved:

openAPIV3Schema:
  type: object
  properties:
    spec:
      type: object
      required: [tier, retentionDays]
      properties:
        retentionDays: { type: integer }
        tier:          { type: string }
      x-kubernetes-validations:
        - rule: "self.tier != 'archive' || self.retentionDays >= 365"
          message: "archive tier requires at least 365 days retention"
        # oldSelf is available for transition rules on update
        - rule: "self.retentionDays >= oldSelf.retentionDays"
          message: "retention may be increased but never reduced"
          optionalOldSelf: false

Google Cloud IAM conditions. Same language, completely different variables, and a useful control:

// Grant expires on 1 September 2026, for buckets named acme-backups*.
request.time < timestamp("2026-09-01T00:00:00Z") &&
resource.type == "storage.googleapis.com/Bucket" &&
resource.name.startsWith("projects/_/buckets/acme-backups")

Time-bound IAM grants are one of the highest-value, least-used features in Google Cloud, and they are a CEL expression in a text box. The same instinct works for AWS through IAM condition keys and for Azure through ABAC conditions, though neither of those uses CEL.

Google Cloud has a third place for the same expressions, custom organization policy constraints, and its failure modes differ enough from Kubernetes to get a section of their own after this walk-through.

7. The authorizer variable

Kubernetes admission hands your expression an authorizer, which lets a policy ask the API server's own RBAC a question. This is unusual and worth knowing about, because it lets you write "this is allowed, but only for principals who already hold a specific permission" without maintaining a parallel list of who those are.

validations:
  - expression: >-
      !has(object.spec.template.spec.hostNetwork) ||
      !object.spec.template.spec.hostNetwork ||
      authorizer.group('policy.csoh.org').resource('hostnetwork')
                .check('use').allowed()
    message: "hostNetwork requires the hostnetwork/use permission"

The first line is the has() lesson again. A Deployment that leaves hostNetwork out, or sets it to false, reaches the expression with no hostNetwork key at all, so without the check the expression errors and failurePolicy decides, which with Fail refuses every ordinary Deployment from anyone who lacks the permission.

The privilege becomes an ordinary RBAC grant on a virtual resource, which means it is granted, reviewed, and audited by the same machinery as everything else, rather than by an annotation somebody added to a namespace two years ago.

Google Cloud custom organization policy constraints

Google Cloud's Organization Policy Service lets you write your own constraints on resource fields, and the condition is CEL. For many Google Cloud teams it is where they first meet CEL, because a custom constraint is what you write when the predefined constraints do not restrict the field you care about. The language is the one above. The evaluator, the variables and the ways it fails without telling you are different, so the failures come first here.

Two objects, and the first one does nothing

A custom constraint is the rule: a resource type, the methods it applies to, a condition and an action. It belongs to an organization, and creating it enforces nothing, as Google's API reference says in as many words. An organization policy turns it on for an organization, folder or project, and by default everything below inherits it. That is the policy and binding split from step 4 again, and it fails the same way: a constraint with no policy looks deployed and does nothing.

name: organizations/ORGANIZATION_ID/customConstraints/custom.bucketRequirePap
resourceTypes:
- storage.googleapis.com/Bucket
methodTypes:
- CREATE
- UPDATE
condition: "resource.iamConfiguration.publicAccessPrevention == 'enforced'"
actionType: ALLOW
displayName: Buckets must enforce public access prevention
description: Set public access prevention to enforced on this bucket.

Save that as bucket-pap.yaml. Field by field, from Google's guide to custom constraints:

Where it fails without telling you

Missing fields behave differently from Kubernetes, and in two directions. The condition is checked against typed fields, so a field the request leaves out is not an error: CEL reads it as its type's default, an empty string, false, zero or an empty list. Google's own Storage Transfer example shows this, refusing a job sent with no logging configuration as an ordinary violation of the constraint, not as an evaluation error. That makes a DENY on a bad value fragile. publicAccessPrevention == 'inherited' catches a request that says inherited, and Google does not document whether a bucket created without the field reaches the condition with the API's default filled in or with an empty string. The ALLOW form above refuses both, so prefer the form whose safe outcome does not depend on the answer.

Map keys go the other way. Reading a label the bucket does not have, resource.labels['env'], is an error, and there is no failurePolicy to choose: Google says the error blocks the create, and for buckets the update too, wherever the policy is enforced. Test the key first with 'env' in resource.labels, the has() lesson from the top of this page. Google's Cloud Storage page also advises tags rather than labels in bucket conditions, because labels are less tightly controlled.

Existing resources are not checked. A constraint is enforced when a resource is created or updated and at no other time, so enforcing one neither reports nor fixes the buckets you already have; Google's Cloud Storage page says existing resources must be updated before a new constraint applies to them. With UPDATE listed, Google's GKE page adds that changes to a cluster already in violation are blocked unless they resolve it.

Method mistakes are mostly loud. Google will not save a constraint that names a method its resource type does not support (its example is UPDATE on Compute Engine images). The quiet one is listing only CREATE for a setting an update can change: a bucket created with public access prevention enforced can have it switched off later with gcloud storage buckets update --no-public-access-prevention, and a CREATE-only constraint never sees that. Some resource types accept only CREATE, Dataflow jobs and VPC routes among them, and for those nothing checks later changes at all.

What resource holds, and which CEL you get

resource is the resource as its REST API represents it, so the condition uses the API's field names: iamConfiguration.publicAccessPrevention, not the public_access_prevention that a plain gcloud storage buckets describe prints (add --raw to see the API's names). Each service publishes the fields you may use, and it is a subset. Cloud Storage offers public access prevention, versioning, retention and labels, among others, and nothing for ACLs or IAM policies.

The CEL is a subset too. Google's general guide covers integer, string, boolean, list and map fields; comparisons; matches, startsWith, endsWith and contains; size() and has(); and the all() and exists() macros. Past that it varies by service. Cloud Storage's examples use in, Pub/Sub's and Cloud KMS's use duration(), and constraints on IAM allow policies do not support ==, in or startsWith on role bindings at all, supplying functions such as RoleNameMatches() instead. filter(), map() and exists_one() from the macro list at the top of this page are not in Google's list, so check the service's page before you reach for one.

Evaluate the condition before Google does

The cel.py harness from step 1 reads pod.json unless DOC names another file. Give it two buckets shaped like the Cloud Storage JSON API's response, trimmed to the fields that matter here, one compliant and one not:

cat > bucket-ok.json <<'EOF'
{"resource": {"kind": "storage#bucket", "name": "acme-audit-logs",
  "location": "US-EAST1", "storageClass": "STANDARD",
  "iamConfiguration": {"publicAccessPrevention": "enforced",
    "uniformBucketLevelAccess": {"enabled": true}},
  "versioning": {"enabled": true}, "labels": {"team": "security"}}}
EOF

cat > bucket-open.json <<'EOF'
{"resource": {"kind": "storage#bucket", "name": "acme-web-assets",
  "location": "US", "storageClass": "STANDARD",
  "iamConfiguration": {"publicAccessPrevention": "inherited",
    "uniformBucketLevelAccess": {"enabled": false}},
  "labels": {"team": "web"}}}
EOF

DOC=bucket-ok.json python3 cel.py "resource.iamConfiguration.publicAccessPrevention == 'enforced'"
DOC=bucket-open.json python3 cel.py "resource.iamConfiguration.publicAccessPrevention == 'enforced'"
resource.iamConfiguration.publicAccessPrevention == 'enforced'
  -> True

resource.iamConfiguration.publicAccessPrevention == 'enforced'
  -> False

True lets the first bucket through, because the action is ALLOW. False refuses the second, with your description as the message. Know the harness's limit: every JSON object here is a map, so a missing key is an error locally even where Google would read a typed field's default. Treat a local error as a question to answer: is that a typed field, which Google reads as its default, or a map key, which Google refuses?

Test, then enforce

Two Google tools answer different questions. Policy Simulator for Organization Policy, generally available since July 2025, answers "what already breaks this?": it takes a constraint and a policy that are not yet set and lists the existing resources that would violate them. A dry-run policy, generally available since December 2023, answers "what would this have blocked?": its rules sit under dryRunSpec instead of spec, violations go to the audit logs, and nothing is denied. Google suggests the simulator first, then a dry run.

The gcloud commands below were not run for this page: every one except the simulator changes an organization's policies, and the simulator needs an organization to run against. The files they read were written and parsed, and the command syntax was checked against Google Cloud SDK 585.0.0. Replace ORGANIZATION_ID and PROJECT_ID first; gcloud projects get-ancestors PROJECT_ID prints the organization a project sits in. This first block writes the dry-run and live policy files and runs the simulator, which sets no policy:

cat > bucket-pap-dryrun.yaml <<'EOF'
name: projects/PROJECT_ID/policies/custom.bucketRequirePap
dryRunSpec:
  rules:
  - enforce: true
EOF

cat > bucket-pap-live.yaml <<'EOF'
name: projects/PROJECT_ID/policies/custom.bucketRequirePap
spec:
  rules:
  - enforce: true
EOF

gcloud policy-intelligence simulate orgpolicy \
  --organization=ORGANIZATION_ID \
  --custom-constraints=bucket-pap.yaml \
  --policies=bucket-pap-live.yaml

When the simulator's list holds no surprises, create the constraint and the dry-run policy. Neither refuses a request: the constraint enforces nothing on its own, and the dry run only logs.

gcloud org-policies set-custom-constraint bucket-pap.yaml
gcloud org-policies set-policy bucket-pap-dryrun.yaml

The next command enforces the constraint: from then on, a request to create or update a bucket in PROJECT_ID is refused unless public access prevention is enforced on the bucket. Run it once the dry run's audit logs show it would block only what you mean it to.

gcloud org-policies set-policy bucket-pap-live.yaml --update-mask=spec

Keep the dry-run and live rules in separate files. Google's examples put spec and dryRunSpec in one file and set it with --update-mask=dryRunSpec, but the source of gcloud org-policies set-policy shows that when no policy exists yet it ignores the mask, prints a warning, and creates the policy from the whole file, so the live spec enforces on the first run. The enforcing command uses --update-mask=spec so the dry run stays in place beside the live rules. Google says a policy can take up to 15 minutes to take effect.

To undo this section, delete the policy, which removes its live and dry-run rules together, and then the constraint. Google's dry-run page gives the first command, and its guide to custom constraints gives the second and says that deleting a constraint also deletes every policy created with it. Their syntax was checked against the Google Cloud SDK 585.0.0 source on 20 November 2026.

gcloud org-policies delete custom.bucketRequirePap --project=PROJECT_ID
gcloud org-policies delete-custom-constraint custom.bucketRequirePap --organization=ORGANIZATION_ID

Hands-on exercises

Run these with the cel.py harness from step 1. Exercises 1 and 2 read pod.json; exercise 5 reads the bucket files from the Google Cloud section.

Exercise 1

Write one expression that is true only when every container both sets runAsNonRoot: true and does not run privileged. Remember that securityContext is optional.

Show the answer
python3 cel.py 'object.spec.containers.all(c,
  has(c.securityContext) &&
  c.securityContext.runAsNonRoot == true &&
  (!has(c.securityContext.privileged) || c.securityContext.privileged == false))'

Two presence checks, at two different depths. The nested one matters because privileged is frequently absent even when securityContext exists, and its absence means false, which is what you want. Writing c.securityContext.privileged == false alone would error on exactly the compliant pods you were trying to allow.

Against the sample this returns false, because of sidecar. Confirm that is the reason rather than assuming: object.spec.containers.filter(c, !has(c.securityContext)).map(c, c.name) names it.

Exercise 2

What does object.spec.nodeName == "" evaluate to, given that pod.json has no nodeName? Predict first, then run it.

Show the answer

It is an error, not false. There is no such key, so the field selection fails and the error propagates out of the whole expression.

This is the most consequential difference between CEL and the languages most people arrive from. In JavaScript you get undefined; in Rego the rule becomes undefined and quietly contributes nothing; in CEL you get a hard error, and inside Kubernetes admission that error is resolved by failurePolicy. With Fail, a typo in a field name blocks every matching deployment in the cluster. With Ignore, the same typo silently disables the control.

The correct forms are has(object.spec.nodeName), or !has(object.spec.nodeName) || object.spec.nodeName == "" if you want to treat absent and empty alike.

Exercise 3

Write a validation that permits a Deployment's replica count to increase but never decrease. Which admission variable do you need, and what breaks on CREATE?

Show the answer
validations:
  - expression: >-
      object.spec.replicas >= oldObject.spec.replicas
    message: "replica count may not be reduced"

oldObject is only populated for UPDATE and DELETE. On CREATE it is null, so dereferencing it errors. Two fixes, and the second is the better habit:

# Guard inside the expression
- expression: >-
    oldObject == null || object.spec.replicas >= oldObject.spec.replicas

# Or keep the expression clean and narrow matchConstraints to UPDATE only
matchConstraints:
  resourceRules:
    - apiGroups: ["apps"]
      apiVersions: ["v1"]
      operations: ["UPDATE"]      # CREATE never reaches this policy
      resources: ["deployments"]

Narrowing the match is preferable when it fits, because it makes the policy's scope legible from the YAML rather than buried in a conditional. It also costs nothing at evaluation time: requests that do not match are never evaluated at all.

Exercise 4

Take this Rego rule and express it as a CEL validation. Then name one thing the Rego version can do that the CEL version cannot.

deny contains msg if {
    some c in input.request.object.spec.containers
    not startswith(c.image, "ghcr.io/acme/")
    msg := sprintf("image %v is not from the approved registry", [c.image])
}
Show the answer
validations:
  - expression: >-
      object.spec.containers.all(c, c.image.startsWith("ghcr.io/acme/"))
    message: "all images must come from ghcr.io/acme/"

The Rego version names the offending image in its message. CEL's message is a fixed string, so the reply cannot say which container failed. There is a messageExpression field that evaluates CEL to build the message, which recovers most of this, and it is worth using: a denial that does not say what to fix generates a support ticket every time it fires.

The larger thing Rego can do is consult data: an allowlist of registries loaded from elsewhere, a mapping of namespaces to permitted teams, anything requiring a join. CEL has no equivalent. Kubernetes closes part of that gap with paramKind and params, which let a binding point at a real cluster object holding configuration, so the allowlist becomes a resource you can RBAC and version rather than a literal in the expression. That pattern is worth reaching for the moment a policy contains a hardcoded list.

Exercise 5

A colleague writes a custom constraint on storage.googleapis.com/Bucket with actionType: DENY to stop buckets labelled exposure: public. The condition is resource.labels['exposure'] == 'public'. Run it against bucket-ok.json from the Google Cloud section, say what it does in Google Cloud to a bucket with no exposure label, and fix it.

Show the answer
DOC=bucket-ok.json python3 cel.py "resource.labels['exposure'] == 'public'"

Locally it is an error, and the last line of what it prints says why:

celpy.evaluation.CELEvalError: ('no such key', <class 'KeyError'>, (StringType('exposure'),))

In Google Cloud a missing map key is a BAD_CONDITION error, and the error blocks the request. So a constraint written to stop public buckets refuses every bucket without an exposure label. Test for the key first:

DOC=bucket-ok.json python3 cel.py "'exposure' in resource.labels && resource.labels['exposure'] == 'public'"
'exposure' in resource.labels && resource.labels['exposure'] == 'public'
  -> False

False means the DENY lets the bucket through.

Common mistakes

Where next