1

I followed the example of https://www.openpolicyagent.org/docs/latest/#5-try-opa-as-a-go-library. Important code snippets:

r := rego.New(
rego.Query("x = data.example.allow"),
rego.Load([]string{"./example.rego"}, nil)
...
rs, err := query.Eval(ctx, rego.EvalInput(input))
...

How can I add external data (data.json) such that I can use, e.g., data.wantedName in the rego policy to access it?

I tried to read through the go doc and the examples but I couldn't find any helpful information.

Thanks!

bogg
  • 31
  • 5
  • There are many ways to load data into OPA, I suggest you take a look here to review them and choose the best for your use case https://dev.to/permit_io/load-external-data-into-opa-the-good-the-bad-and-the-ugly-26lc – Oded BD Apr 05 '22 at 12:04

1 Answers1

6

Have you seen the docs on rego.Store() and this example?

Something along these lines should do the trick for simple cases:

    data := `{
        "example": {
            "users": [
                {
                    "name": "alice",
                    "likes": ["dogs", "clouds"]
                },
                {
                    "name": "bob",
                    "likes": ["pizza", "cats"]
                }
            ]
        }
    }`

    var json map[string]interface{}

    err := util.UnmarshalJSON([]byte(data), &json)
    if err != nil {
        // Handle error.
    }

    store := inmem.NewFromObject(json)

    // Create new query that returns the value
    rego := rego.New(
        rego.Query("data.example.users[0].likes"),
        rego.Store(store))

You could implement your own storage for more intricate uses, but that's going to be a lot more involved. If you get by with feeding inmem.NewFromObject() stores into rego.New(), you should try that first.

sr_
  • 547
  • 5
  • 14
  • 2
    In addition to this answer, one might want to check out the new SDK: https://blog.styra.com/blog/the-open-policy-agent-sdk-overview – Devoops Oct 08 '21 at 11:36
  • @sr_ Yes, I tried that but I load the policy (`rego.policy`) in `rego.New` as well. I don't know how to combine both of them into the `rego.New` statement. – bogg Oct 08 '21 at 11:48
  • @Devoops thanks for that link! As I followed some links in this article I come across the ability to use `bundles` and now I see I can use bundles in the go lib as well. I will look into that. – bogg Oct 08 '21 at 12:07
  • @bogg yeah, it essentially allows you to run OPA as if you would be running from the command line, with config file and all that goodness :) – Devoops Oct 08 '21 at 17:56