Header Ads

Using OPA(Open Policy Agent) in Kubernetes

 

What is OPA(Open Policy Agent):

OPA is an open-source extension that can be used in Kubernetes as a policy agent. It allows us to write customised policies for enforcing our own rules in our Kubernetes cluster. 



In general if we make a CREATE resource request to K8s, it passes through following 3 phases in kube-apiserver:

a) Authentication
b) Authorization
c) Admission Control

The Authentication stage asks and verifies "WHO is making the request".

The Authorization stage checks if the requestor has correct privileges to create the specified resource.

If the above two stages are completed successfully, then kube-apiserver checks if we have any AdmissionController enabled. OPA(Open Policy Agent) is a kind of admission controller used by kube-apiserver. We can define our own rules for the OPA and then the OPA will ensure that our kube-apiserver will strictly follow these rules.


Example rule:
"Only allow to create deployments with minimum 2 replicas" 

If we define such rules for the OPA then it will make sure Kubernetes wont be able to create new deployments if the replica count in less than 2.

OPA is not only specific to Kubernetes, it allows unified context aware policy enforcement across the whole stack. OPA allows easy implementation of policies and uses "REGO" language for policies. "REGO" can easily be integrated with JSON and YAML formats and we will see an example later in this post. 


What is OPA GateKeeper:


Open Policy Agent does not understand any Kubernetes resource like pods, deployments, config-maps etc. The OPA GateKeeper makes it easier to use OPA with Kubernetes by creating CRD's (Custom Resource Definitions) for Kubernetes. OPA Gatekeeper creates a CRD called as "ConstraintTemplate". We can use the "REGO" policies in these ConstraintTemplate resources, 
After we have a ConstraintTemplate, we can create multiple Constraint resources in our Cluster.



Example: Using OPA GateKeeper to enforce minimum replica count as 2:

i) Create a ConstraintTemplate "Minimum2Replicas" as shown below:



ii) Create a Constraint from the above ConstaintTemplate.


Applying these YAML resources will ensure that in our cluster we can only create deployments with minimum 2 replicas.

No comments

Powered by Blogger.