2

I'm learning OPA and rego. I'm trying to write a simple policy and have the same evaluated through VSCode Plugin.

Folder Structure:

enter image description here

learning.rego

package learning

test {
    a := "test"
    a == "test"
}

input.json

{}

And when I choose "OPA: Evaluate Selection" option from the command pallete, I get the below error.

{
  "errors": [
    {
      "message": "expected body but got *ast.Package"
    }
  ],
  "metrics": {
    "timer_rego_load_bundles_ns": 919639,
    "timer_rego_module_compile_ns": 481890,
    "timer_rego_module_parse_ns": 55722,
    "timer_rego_query_parse_ns": 22773
  }
}

But the same policy is working as expected in rego playground and evaluates to "true" as expected. What am I missing here?

3 Answers3

2

Try running "Evaluate Package" instead of "Evaluate Selection", and it should work.

The Open Policy Agent extension for VSCode offers three ways of evaluating Rego code:

  1. Evaluate Package

This seems to be the one you want. This parses the selected Rego code as an entire package. It expects the selection to begin with a Package declaration (e.g. package learning). If you select the entire Rego package and run "Evaluate Packages", it should work.

  1. Evaluate Selection

This option evaluates part of a Rego package, so it expects the selection to begin with a Body (e.g. your test definition). If you just select test and its definition, it should work.

  1. Partially Evaluate Selection

This final option is a bit more complex. In essence, rather than evaluating the policy it returns the conditions under which the policy is satisfied. This is useful for building queries for external datastores, or for interacting with complex data.

Will Beason
  • 3,417
  • 2
  • 28
  • 46
  • Thank You @Will for the response. "Evaluate Package" works fine but I wanna evaluate policies as I write and I thought "Evaluate Selection" would be a right choice but it is not working as expected. I highlighted the policy body as suggested and running evaluate selection return a similar error as above. Selected Policy: ` test { a := "test" a == "test" } ` Error Response: ` { "errors": [ { "message": "expected body but got *ast.Rule" } ], "metrics": { // redacted to save space. } } ` – Sulbigar Shanawaz Jun 09 '21 at 14:34
  • I feel the plugin's "Evaluate Package" is not working as expected or I'm running it in a totally wrong way. – Sulbigar Shanawaz Jun 11 '21 at 19:28
0

In vs code press ctrl+p and search for >OPA: Evaluate Package and enter you'll see the result.

enter image description here

M123
  • 1,203
  • 4
  • 14
  • 31
0

To use Evaluate Selection

Double click on the policy name, in your case, test

Now run Evaluate Selection It should work fine.

Refer to this website for more info: link

For your specific case, read up Chapter 2.