user-interfaceopen-policy-agentrego

How to build OPA Rules from JSON


Is there some program or feature that can turn a JSON object into a policy.rego file?

I am aware there is currently a feature to turn a rego file into a JSON, but have not found anything to reverse this process. I am creating a UI where I hope to be able to interact with the policy.rego file. My thought process was I would create the UI to interact/edit the json file and then turn that into a rego file.

I am open to any suggestions about how to go about this process or if I should do something entirely different. My main goal is to be able to edit the policy.rego on the fly and allow those with little to no experience with OPA make simple edits as well.

I was unable to find any documentation about converting a json into a rego file. I also was unable to find any documentation about OPA UIs.


Solution

  • Not by CLI commands alone, but assuming you're comfortable working with a JSON representation of Rego's abstract syntax tree (AST), and some Go code, it's doable.

    1. Use opa parse --format json command pointed at any Rego file to have its JSON AST printed. Pipe that to a file and modify to your liking.
    2. There isn't any equivalent command to "unparse" the JSON AST back to Rego, but if you're comfortable writing some Go code, you can unmarshal your JSON to a Module.
    3. Hand the module to the formatter, which will (unsurprisingly) format it back to Rego.