OPA in Kubernetes and Policies Playground

Open Policy Agent is a project that uses rego files to enforce policies on your kubernetes cluster while v1.26 is starting to roll out some features in beta that are more native to kubernetes. You have many pluggable options to use such as gate-keeper/kyverno are most notable in this space again this will serve as a part to see what other mechanisms you can place inside your cluster as guard rails.

A quick way to get started is run through the installation on the page linked below.

https://www.openpolicyagent.org/docs/latest/#running-opa

Once installed you can use the following command for more commands

./opa 

As far as how OPA aides in Kubernetes this is a good depiction provided by the documentation shown below

Credit: https://www.openpolicyagent.org/docs/latest/kubernetes-introduction/

The provided code block will give a example of blocking specific registries that are not allowed

package kubernetes.admission

deny[reason] {
  some container
  input_containers[container]
  not startswith(container.image, "hooli.com/")
  reason := "container image refers to illegal registry (must be hooli.com)"
}

#you can tailor the not startswith(container.image, "<your repository registry>"
input_containers[container] {
  container := input.request.object.spec.containers[_]
}

input_containers[container] {
  container := input.request.object.spec.template.spec.containers[_]
}

You can also use the test playground provided by Strya

To test out your rego file prior to applying it to understand the impact.

After hitting the evaluate function we can see the output of what is interpreted

./opa run -s

This is telling OPA to run as a server this will prompt a response and let you know it is running along with initialization time.

After we have a policy we will have to load the policy with the following command

curl -X PUT --data-binary @example.rego http://localhost:8181/v1/policies/example1

So on the running terminal we leave the OPA server hanging as we run the PUT request we can see the server registered it with the request along with the level “info”

We are missing some other components that go together with kubernetes for enforcement this was to show the overview how policies can be applied but also the simplicity of rego that is understandable to what resources to restrict or outright deny.

While this isn’t a full encompassing blog post you’ll like to explore this further I’ve found some resources that cover this more extensively and some out of the box at least Azure Kubernetes Service does come out of the box with gate-keeper.

Strya the original creators of OPA provide very detailed information to help you out along with the developer academy to learn how to enforce across other resources such as terraform.

https://docs.styra.com/systems/kubernetes/admission-control