opa fmt: Format and Check Rego in CI
opa fmt --fail policy/ exits non-zero if any Rego file is not formatted to OPA canonical style.
opa fmt is the gofmt of Rego. In CI you run it in check mode so policy files stay consistently formatted across contributors.
What it does
opa fmt rewrites Rego source to the canonical format. By default it prints the formatted result; -w writes in place; --list names files that need formatting; --fail makes it exit non-zero if any file is not already formatted, which is the CI gate.
Common usage
# format in place
opa fmt -w policy/
# CI gate: fail if any file is unformatted
opa fmt --fail --list policy/
# show the diff of what would change
opa fmt --diff policy/Options
| Flag | What it does |
|---|---|
| -w, --write | Rewrite files in place |
| -l, --list | List files that need formatting |
| -d, --diff | Print a diff instead of the formatted file |
| --fail | Exit non-zero if formatting is needed |
In CI
Run opa fmt --fail --list policy/: --fail makes an unformatted file a non-zero exit (build failure) and --list names the offenders in the log. Contributors then run opa fmt -w locally to fix. This keeps policy reviews focused on logic, not whitespace.
Common errors in CI
With --fail, an unformatted file just exits non-zero after --list prints the paths; run opa fmt -w to fix. rego_parse_error: unexpected token means the file will not parse, so it cannot be formatted; fix the syntax first. command not found: opa means the OPA binary is not installed on the runner.