Reputation: 41
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!
Upvotes: 2
Views: 3002
Reputation: 602
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.
Upvotes: 7