Search code examples
open-policy-agentrego

Evaluating multiple files from a folder using opa eval command


I have seen this on the OPA website that I could use the following:

To Evaluate a policy on the command line. ./opa eval -i input.json -d example.rego

In my case, I have multiple input files and I have modified it to

./opa eval -i /tmp/tfplan.json -d /tmp/example.rego -d /tmp/input1.json -d /tmp/input2.json

Rather than specifying the files as input1, input2 and so on individually, can I directly modify it to read all the json files present in the tmp folder?


Solution

  • Yes! The CLI will accept directories for the -d/--data and -b/--bundle parameters and recursively load files from them.

    Ex with:

    /tmp/foo/input1.json
    /tmp/foo/input2.json
    

    opa eval -d /tmp/foo/input1.json -d /tmp/foo/input2.json ..

    Is the same as

    opa eval -d /tmp/foo ..

    Keep in mind that -d/--data will attempt to load ANY files found in the directory, which can sometimes lead to conflicts (eg, duplicate keys in the data document) or loading incorrect files. So be careful about pointing at /tmp as its likely to include additional files you didn't neccisarily want (note the example above used a sub-directory). Typically we recommend using -b/--bundle and providing files as data.json with a directory structure following the bundle spec https://www.openpolicyagent.org/docs/latest/management/#bundle-file-format which can help avoid most of those common problems.