A red and white boom barrier and a no-entry sign closing a road at a checkpoint, with the article title about generating OPA Rego policies with an LLM
Cover based on a photo by Alexander Roumega, via Wikimedia Commons, CC0 1.0

You can generate OPA Rego policies with an LLM in seconds, and most drafts look right. Some won't parse on a current OPA release because the model learned an older syntax. Worse, some will parse, pass a quick look and still let through the exact Pod the policy was written to stop. Using an LLM for Rego works when the model drafts and OPA decides: opa check for syntax and compile errors, and opa test with cases you wrote before you read the model's answer.

This guide walks through that loop on one Kubernetes admission policy: deny Pods that run a privileged container or pull an image from outside the company registry. Every error message and test result below comes from running OPA 1.22.4 on the policies shown, on a Linux lab box. The drafts were written for this guide to show mistakes models commonly make; they are not a captured model transcript. Model output is never the evidence.

It's the policy-as-code sibling of our guides to generating Semgrep rules with an LLM and CodeQL queries. Same idea, different validator.

Defensive and authorized work only. Write and test policies for clusters, repositories and APIs you own or were hired to protect. Keep internal hostnames, registry credentials and real manifests out of prompts unless you're cleared to share them. See what to send the model below.

Why use an LLM for OPA Rego policies

Open Policy Agent evaluates policies written in Rego against JSON input. The same engine handles Kubernetes admission control, infrastructure-as-code checks and API authorization. The OPA Kubernetes docs put the admission case plainly: "Admission Controllers enforce policies on objects during create, update, and delete operations."

Rego is a good fit for model help and a bad fit for trusting it. Rego is declarative: a rule body is a set of conditions that must all hold, and an undefined value quietly makes a rule not fire instead of raising an error. A model is fast at the boilerplate, helper rules and sprintf messages. It is weaker on which fields of the input actually exist, and on the syntax change that came with OPA 1.0.

How to check an LLM-generated Rego policy

There are two separate questions:

  1. Does it compile? opa check parses and compiles the policy. --strict turns on compiler strict mode, which also rejects unused local assignments and unused imports.
  2. Does it decide correctly? Compiling says nothing about this. You need unit tests: a case that must be denied, a look-alike that must be allowed, and the edge cases a reviewer would ask about.

The OPA policy testing docs describe tests as "standard Rego rules with a convention that the rule name is prefixed with test_", run with opa test. Write the tests first, from the requirement, so the model's draft can't shape what you check.

Diagram of the loop to generate OPA Rego policies with an LLM: the model drafts Rego, opa check parses and compiles it, opa test runs true-positive and look-alike cases, exact errors and failing tests go back to the model, and only passing policies reach admission control
Write tests first, return exact compiler errors and failing tests to the model, and admit only policies that pass both checks. Image: RedRouter, Original

Step 1: Write the tests before you prompt

The requirement: deny any Pod with a privileged container, and deny any image not from registry.example.com/. Six tests cover it:

package kubernetes.admission_test

import data.kubernetes.admission

pod(spec) := {"request": {"kind": {"kind": "Pod"}, "object": {"spec": spec}}}

test_privileged_container_denied if {
	count(admission.deny) == 1 with input as pod({"containers": [
		{"name": "app", "image": "registry.example.com/app:1.4", "securityContext": {"privileged": true}},
	]})
}

test_privileged_init_container_denied if {
	count(admission.deny) == 1 with input as pod({
		"initContainers": [{"name": "setup", "image": "registry.example.com/setup:2", "securityContext": {"privileged": true}}],
		"containers": [{"name": "app", "image": "registry.example.com/app:1.4"}],
	})
}

test_public_registry_denied if {
	count(admission.deny) == 1 with input as pod({"containers": [{"name": "app", "image": "docker.io/library/nginx:1.29"}]})
}

test_lookalike_registry_denied if {
	count(admission.deny) == 1 with input as pod({"containers": [{"name": "app", "image": "registry.example.com.attacker.test/app:1.4"}]})
}

test_clean_pod_allowed if {
	count(admission.deny) == 0 with input as pod({"containers": [
		{"name": "app", "image": "registry.example.com/app:1.4", "securityContext": {"privileged": false}},
	]})
}

test_non_pod_ignored if {
	count(admission.deny) == 0 with input as {"request": {"kind": {"kind": "ConfigMap"}, "object": {}}}
}

Two of these are the ones a model is likely to miss. Kubernetes runs init containers in their own list, initContainers, separate from containers, and a privileged init container is still privileged. And registry.example.com.attacker.test starts with the string registry.example.com.

Then prompt with the requirement, the input shape and the test file:

Write an OPA Rego v1 policy, package kubernetes.admission, that defines deny as a set of messages for a Kubernetes AdmissionReview. Deny Pods with any privileged container and any image not from registry.example.com/. It must pass the tests below. Return Rego only. [paste the test file and one sample AdmissionReview]

Step 2: Run opa check on the draft

Ask without saying "v1" and a first draft often looks like this:

package kubernetes.admission

deny[msg] {
  input.request.kind.kind == "Pod"
  container := input.request.object.spec.containers[_]
  container.securityContext.privileged
  msg := sprintf("container %v is privileged", [container.name])
}

That was standard Rego for years, and it's all over older blog posts and repositories. OPA 1.22.4 rejects it:

$ opa check policy.rego
2 errors occurred during loading:
policy.rego:3: rego_parse_error: `if` keyword is required before rule body
policy.rego:3: rego_parse_error: `contains` keyword is required for partial set rules

The OPA v1.0 upgrade guide explains the change: in OPA v1.0, in, every, if and contains "are part of the language by default", and rule heads must use if and contains. You have two fixes. Send the exact error back and ask for Rego v1, or convert it yourself with opa fmt --v0-v1, which on this draft added import rego.v1 and rewrote the head to deny contains msg if. The v0 compatibility docs also describe a --v0-compatible flag. Use that to keep running old policies while you migrate, not as a reason to accept new v0 code from a model.

Step 3: Run the tests

The second draft is valid Rego v1:

package kubernetes.admission

deny contains msg if {
  input.request.kind.kind == "Pod"
  some container in input.request.object.spec.containers
  container.securityContext.privileged == true
  msg := sprintf("container %v is privileged", [container.name])
}

deny contains msg if {
  input.request.kind.kind == "Pod"
  some container in input.request.object.spec.containers
  not startswith(container.image, "registry.example.com")
  msg := sprintf("image %v is not from registry.example.com", [container.image])
}

opa check --strict exits 0 on it. A reviewer skimming it would probably approve it too. opa test doesn't:

$ opa test . -v
...
data.kubernetes.admission_test.test_privileged_init_container_denied: FAIL (1.295495ms)
...
data.kubernetes.admission_test.test_lookalike_registry_denied: FAIL (1.782789ms)
...
PASS: 4/6
FAIL: 2/6

Both failures are silent allows, the worst kind of policy bug:

  • Init containers are never checked. The rules only walk spec.containers. A privileged init container passes. So would one in ephemeralContainers, the list Kubernetes uses for ephemeral debugging containers.
  • The registry check is a string prefix without a slash. startswith(image, "registry.example.com") is true for registry.example.com.attacker.test/app:1.4.

To see what that means at admission time, we ran one Pod that breaks both rules through opa eval: a privileged init container plus an image from the look-alike registry. Draft 2 returned [], which means admit.

The verbose test output also prints a trace for each failure, pointing at the line where evaluation stopped. Paste the failing test names and that trace back to the model. "Fix it" without the trace gets you a guess.

Step 4: The final policy

package kubernetes.admission

allowed_registry := "registry.example.com/"

pod_containers contains c if {
	some field in ["containers", "initContainers", "ephemeralContainers"]
	some c in input.request.object.spec[field]
}

deny contains msg if {
	input.request.kind.kind == "Pod"
	some c in pod_containers
	c.securityContext.privileged == true
	msg := sprintf("container %v is privileged", [c.name])
}

deny contains msg if {
	input.request.kind.kind == "Pod"
	some c in pod_containers
	not startswith(c.image, allowed_registry)
	msg := sprintf("image %v is not from %v", [c.image, allowed_registry])
}

On OPA 1.22.4, opa check --strict exited 0, opa test . -v passed 6 of 6, and opa test --coverage reported 100% coverage of the policy file. The same Pod that draft 2 admitted now gets two denials:

$ opa eval --format=pretty -d policy.rego -i input.json "data.kubernetes.admission.deny"
[
  "container setup is privileged",
  "image registry.example.com.attacker.test/app:1.4 is not from registry.example.com/"
]

opa fmt rewrote our two-space indentation to tabs and changed nothing else, which is why the final policy and the test file use tabs. Run opa fmt on every model draft so diffs in review show logic, not whitespace.

A coverage number only means every line ran under some test. It doesn't mean the tests are complete. This policy still doesn't cover Pod templates inside Deployments or Jobs, image digests, or hostPID and host-path mounts. Add each as a test first, then ask for the change.

Step 5: Keep it in CI

Put the policy and its tests in the same repository, and run the same commands on every change:

opa fmt --list --fail .
opa check --strict .
opa test . -v

All three exited 0 on the final policy and tests. Before we ran opa fmt, the first command exited 2 and listed the test file, so expect it to catch hand-edited or model-pasted Rego too.

A model edit that breaks syntax fails at opa check. A model edit that quietly widens what's allowed fails at opa test, as long as there's a test for it. When a policy is wrong in production, add the case that slipped through as a new test before you touch the policy.

What to send the model

  • Requirement and tests, yes. They describe what you want, not what you run.
  • Sample input, only scrubbed. Replace namespaces, internal hostnames, service account names and registry paths with placeholders. A fake AdmissionReview that keeps the shape works just as well.
  • Existing policies, carefully. A full policy library maps exactly what your cluster allows. Send the one rule you're changing.
  • Check retention first. On RedRouter, Zero Data Retention is an opt-in setting and off by default. The data handling docs explain what is stored and how to turn it on. Our post on what RedRouter keeps covers the same ground in plain terms.

Automating the loop

The draft-check-test loop scripts easily, because opa check exited 1 on the v0 draft and opa test exited 2 when tests failed. This sketch asks a model for a policy, runs both commands, and sends any errors back until the tests pass. It uses the OpenAI Python SDK with RedRouter's https://redrouter.org/v1 base URL, as covered in our OpenAI-compatible API guide and the RedRouter quickstart.

import os, subprocess, pathlib
from openai import OpenAI

client = OpenAI(base_url="https://redrouter.org/v1", api_key=os.environ["REDROUTER_API_KEY"])
tests = pathlib.Path("policy_test.rego").read_text()
task = ("Write an OPA Rego v1 policy, package kubernetes.admission, defining deny as a set of "
        "messages. Deny Pods with any privileged container and any image not from "
        "registry.example.com/. It must pass these tests. Return Rego only.\n\n" + tests)
messages = [{"role": "user", "content": task}]

for attempt in range(4):
    reply = client.chat.completions.create(model="glm-5.3-flash-red", messages=messages)
    rego = reply.choices[0].message.content.strip().removeprefix("```rego").removesuffix("```").strip()
    pathlib.Path("policy.rego").write_text(rego + "\n")
    check = subprocess.run(["opa", "check", "--strict", "."], capture_output=True, text=True)
    test = subprocess.run(["opa", "test", ".", "-v"], capture_output=True, text=True) if check.returncode == 0 else check
    print(test.stdout or test.stderr)
    if check.returncode == 0 and test.returncode == 0:
        break
    messages += [{"role": "assistant", "content": rego},
                 {"role": "user", "content": "OPA reported:\n" + test.stdout + test.stderr + "\nFix the policy. Rego only."}]

The loop never edits the test file. If a model "passes" by changing the tests, it hasn't passed. Review the final diff yourself before it goes anywhere near a cluster.

Choosing a model

Use any model that follows a "Rego only" instruction and can hold a test file plus a few rounds of errors. On RedRouter, GLM 5.3 Flash Red (glm-5.3-flash-red) costs $0.25 per 1M input tokens, $0.10 per 1M cached input tokens and $1.00 per 1M output tokens. red-cyber-1 (Beta), the featured model for authorized penetration testing and red-team work, is $0.28 / $0.10 / $1.10 per 1M tokens. See pricing and the models page for current rates.

Policy work is usually uncontroversial, but prompts about container escapes, privileged Pods or bypassing admission control can trip refusals on mainstream assistants, even when you're hardening your own cluster. The RedRouter security page explains how the service is meant for authorized work. Whatever model you use, judge it by one thing: whether its policy passes tests you wrote first.

Common Rego mistakes in LLM drafts

MistakeHow it shows upWhat to tell the model
Rego v0 rule heads (deny[msg] { ... })rego_parse_error: if keyword is requiredWrite Rego v1, or run opa fmt --v0-v1
Only walking spec.containersPrivileged init container admittedCheck initContainers and ephemeralContainers too
Registry prefix without a slashregistry.example.com.attacker.test admittedMatch registry.example.com/
Wrong input path (object.containers)Compiles; rule never firesPaste a real AdmissionReview shape
Changing tests to passTests green, requirement not metTests are fixed; only the policy may change
Treating 100% coverage as doneMissing cases never testedAdd a test for each new requirement first

FAQ

Can an LLM write OPA Rego policies?

Yes, as a first draft. Expect older v0 syntax, rules that only check part of the input, and string checks that are looser than they look. Treat the draft as untrusted until it passes opa check --strict and tests you wrote before prompting.

How do I validate a Rego policy?

Run opa check --strict for parse and compile errors, then opa test . -v against unit tests. Tests are Rego rules whose names start with test_, usually in a package ending in _test. Include at least one case that must be denied and one look-alike that must be allowed.

Why does OPA say "if keyword is required before rule body"?

The policy uses Rego v0 syntax, and OPA 1.0 and later default to Rego v1. Add if before rule bodies and contains to partial set rules, or convert the file with opa fmt --v0-v1. The --v0-compatible flag runs old policies during a migration.

Does opa check catch logic bugs?

No. In our lab a policy that admitted a privileged init container and a look-alike registry passed opa check --strict with exit 0. Only the tests caught it.

Is this the same as OPA Gatekeeper?

No. Gatekeeper is a separate project that integrates OPA with Kubernetes through its own custom resources. The Rego testing loop here applies to the policy logic either way, but Gatekeeper policies read the request under input.review, so build test inputs to match what your deployment actually passes in.

How is this different from a Semgrep or CodeQL rule?

Rego decides whether a request or config is allowed at the time it's evaluated. Semgrep and CodeQL find patterns in source code. See Semgrep rules with an LLM and CodeQL queries with an LLM, and LLM secure code review for reviewing your own code.

Is it safe to paste Kubernetes manifests into an LLM?

Not raw ones, unless you're cleared to. Send the requirement, the tests and a scrubbed input instead. On RedRouter, Zero Data Retention is opt-in and off by default; the data handling docs explain what's stored.

Sources