OPA (Open Policy Agent): Part-1: Rego Basics

Share At:

Open Policy Agent | Policy Language

Policy Language

OPA is purpose built for reasoning about information represented in structured documents. The data that your service and its users publish can be inspected and transformed using OPA’s native query language Rego.

What is Rego?

Rego was inspired by Datalog, which is a well understood, decades old query language. Rego extends Datalog to support structured document models such as JSON.

Rego queries are assertions on data stored in OPA. These queries can be used to define policies that enumerate instances of data that violate the expected state of the system.

Installing OPA

If this is your first time using OPA, download the latest executable for your system.

On macOS (64-bit):

curl -L -o opa https://github.com/open-policy-agent/opa/releases/download/v0.11.0/opa_darwin_amd64

On Linux (64-bit):

curl -L -o opa https://github.com/open-policy-agent/opa/releases/download/v0.11.0/opa_linux_amd64

Windows users can obtain the OPA executable from GitHub Releases. The steps below are the same for Windows users except the executable name will be different.

Set permissions on the OPA executable:

chmod 755 ./opa

Configuring VSCode Plugin For OPA

To use OPA with your Vscode Editor, Install below OPA plugin:


Writing Your First Policy and Testing it

Lets write our first basic policy named “policy.rego” and test it:

policy.rego

package policy
default allow = false

allow = true {
    1 == 1
}

Testing Policy:

  1. Press Ctrl+Shift+p in your keyboard and it will open command pellet like below:
  1. Search for OPA:Evaluate Package and click it. Once done, You will see output.json at the right. The Policy evaluates to true since “1 == 1”.
  1. Alternatively, you may also evaluate policy using below command from your Vscode Terminal:
opa eval --data policy.rego 'data.policy.allow'

The output of the above command will be like below:

{
  "result": [
    {
      "expressions": [
        {
          "value": true,
          "text": "data.policy.allow",
          "location": {
            "row": 1,
            "col": 1
          }
        }
      ]
    }
  ]
}
  1. Now let’s check Fail case scenario. Let’s change policy a bit to return it to false:

policy.rego after update

package policy

default allow = false

allow = true {
    1 == 2
}
  1. Now lets evaluate the policy now. It should return false.
  1. As we have predicted, the policy has returned false. see below:

That’s conclude our first tutorial on OPA and Rego.

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