Running simple Open Policy Agent Playground example from CLI

Viewed 460

It's not clear to me how to run the Simple Example from the Open Policy Agent Playground from the CLI.

play.rego

package play
default hello = false

hello {
    m := input.message
    m == "world"
}

input.json

{
    "message": "world"
}

I tried using:

opa eval -i input.json -d play.rego "data.play.hello"

But, I could not get this result

{
    "hello": true
}

Unfortunately, I got this: :(

{
  "result": [
    {
      "expressions": [
        {
          "value": true,
          "text": "data.play.hello",
          "location": {
            "row": 1,
            "col": 1
          }
        }
      ]
    }
  ]
}

I thought others might find it useful to understand how to run these example from the CLI, so I had to ask.

1 Answers

That's a great question! Unless "evaluate selection" is selected, the Rego Playground always evaluates the entire policy, i.e. all rules included. When you query a policy using opa eval you can either choose to do the same, or as you do in your example - query just a single rule for its value.

If you change the query from "data.play.hello" to just "data.play" it will evaluate the full policy just like the playground:

$ opa eval -i input.json -d play.rego "data.play"
{
  "result": [
    {
      "expressions": [
        {
          "value": {
            "hello": true
          },
          "text": "data.play",
          "location": {
            "row": 1,
            "col": 1
          }
        }
      ]
    }
  ]
}

If you only want to display the actual output without all the details around it, you could use one of the formatting options available for opa eval such as --format raw:

$ opa eval --format raw -i input.json -d play.rego "data.play"
{"hello":true}
Related