JD Allen
JD Allen

Reputation: 944

Retrieve a value from a set where the key comes from another set in Open Policy Agent (OPA)

I've read through the OPA 'Policy Language' page, but my problem is only sorta addressed...looking for clarity here ;)

I have two sets:

"servers": {
  "server1": [ "silver" ],
  "server2": [ "gold" ]
}

"plan": {
  "gold": [ "1000" ],
  "silver": [ "100" ]
}

in my data section. I need a rule that given input.server = "server2" will return "1000" ...so a set lookup that provides the key for a second lookup.

I was trying this:

rate msg = {
  p := servers[input.server]
  msg := plan[p]
}

but OPA barfs all over that. It looks do-able to me, but not having any success in coming up with the rule for this. Thanks!

Upvotes: 0

Views: 1071

Answers (1)

Devoops
Devoops

Reputation: 2315

servers[input.server] is going to return a list ([ "1000" ]) and not "1000", so you'd need to get the item out of the list if you want to use it as the key to look up in the plan object. Additionally, the rate rule had some syntax wrong. This should work:

servers := {
    "server1": ["silver"],
    "server2": ["gold"]
}

plan := {
    "gold": ["1000"],
    "silver": ["100"]
}

rate = msg {
    p := servers[input.server][0]
    msg := plan[p]
}

Finally, and not meant as nitpicking :), but there aren't any sets in your data - only lists and maps. Use curly brackets, i.e. { "1000" } instead of [ ] if you want those.

Upvotes: 1

Related Questions