On this page
Rego is a policy language used by Open Policy Agent(OPA) to define policies against different data formats such as json, yaml, hcl, etc. An ideal tool for evaluating structured data you will encounter often as an engineer. The declarative language allows individuals to implement security, compliance, governance, and best practices evaluations all in one language. Rego is often used in many static code analysis tools for that reason. In this exercise you will learn how to put this into practice.
Learning rego can be a daunting task but a vital one to mature your understanding of static code analysis within the infrastructure security space. The best resource to learn rego in my opinion is OPA Policy Authoring by Styra.
To get started in understanding how to use rego, let’s take a look at a very simple example on the Rego Playground. Below contains the json we want to evaluate in which we want to test if the input type is
user and the name is
The policy below is what we are using to test the above json to see if the input type is
user and the input name is
admin. It will default to
false if either or is not the case and
true if both are true. The
input variable accesses the json document.
Open Policy Agent
Now lets take what we have learned from above and use rego. To install OPA be sure to visit the get started guide on the Open Policy Agent documentation or use
brew install opa. Save the above files as
data.json, and then run the command
opa eval -d policy.rego -i data.json "data"
Conftest has a wide variety of examples in their repository which I would strongly recomment reviewing and learning from. Lets start with a simple example to fail if your deployment does not have an owner label.
To give you an idea of what you can query when it comes to rego with structured data here are some examples of what you can query using the rego language.
- Docker compose
Save this file as
Save this file as
Then run the command
conftest test deployment.yaml --policy policy.rego to start evaluating your deployment file.
Now uncomment lines 5-6 adding the owner label to your deployment.