OPA (Open Policy Agent): Part-3: Rego – Loops & Input Variable

Share At:

What is Open Policy Agent? - Code The Cloud

Overview

In this article, we are going to learn about Loops in Rego as well as how we can pass input variable to OPA policy.

Note: Loops in rego are defined as [ _ ]

We will see how we can iterate over a json file and evaluate if the policy is true or false.

Working Example

Let’s create a Directory called test4 and create 2 files like below:

policy.rego

package policy

default allow = false

allow {
    input.user.roles[_] == "admin"
}

input.json

{
    "user": {
        "username": "test_user",
        "roles": ["developer","admin"]
    }
}

Testing the policy

Since now we have created 2 files called “policy.rego” and “input.json”, let’s test our policy now.

The policy will iterate over all the roles and if it finds a roles as “admin”, it will return true.

Let’s test this now:

Method-1: Let’s run below command:

opa eval --input input.json --data policy.rego 'data.policy.allow'

The output will be something like below:

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

Note: If you forget to mention input parameter in the above command, the command will return false.

opa eval --data policy.rego 'data.policy.allow'

Method-2: We can test our policy in one more way. Now let’s run below command:

opa eval --input input.json --data policy.rego 'data.policy.allow' --format pretty

The output will be like below:

true

Testing Fail Case Scenario

Now let’s test the fail case scenario. Let’s change our input.json file and remove the “admin” role from user “test_user”:

Note: The policy.rego file will remain unchanged.

policy.rego

package policy

default allow = false

allow {
    input.user.roles[_] == "admin"
}

input.json

{
    "user": {
        "username": "test_user",
        "roles": ["developer"]
    }
}

Now test the policy. This should return “false” since we have removed “admin” role from “test_user”.

opa eval --input input.json --data policy.rego 'data.policy.allow'

Output:

{
  "result": [
    {
      "expressions": [
        {
          "value": false,
          "text": "data.policy.allow",
          "location": {
            "row": 1,
            "col": 1
          }
        }
      ]
    }
  ]
}

Alternatively, we can test like below:

opa eval --input input.json --data policy.rego 'data.policy.allow' --format pretty

Output:

false

This concludes our 3rd tutorial on rego loops and OPA.

Happy Learning !!


Share At:
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Back To Top

Contact Us