Extending Security Using Open Policy Agent
local graph
Chapter 11 — Extending Security Using Open Policy Agent
Section titled “Chapter 11 — Extending Security Using Open Policy Agent”So far, we have covered Kubernetes’ built-in authentication and authorization capabilities, which help to secure a cluster. While this will cover most use cases, it doesn’t cover all of them. Some security best practices that Kubernetes can’t handle are pre-authorizing container registries and ensuring that Ingress objects don’t overlap (though most Ingress controllers do check, such as NGINX).
These tasks are left to outside systems and are called dynamic admission controllers. Open Policy Agent (OPA) and its Kubernetes native sub-project, Gatekeeper, is one of the most popular ways to handle these use cases. This chapter will detail the deployment of OPA and Gatekeeper, how OPA is architected, and how to develop policies.
In this chapter, we will cover the following topics:
- Introduction to dynamic admission controllers
- What is OPA and how does it work?
- Using Rego to write policies
- Enforcing Ingress policies
- Mutating objects and default values
- Creating policies without Rego
Once you’ve completed this chapter, you’ll be on your way to developing and implementing important policies for your cluster and workloads.
Technical requirements
Section titled “Technical requirements”To complete the hands-on exercises in this chapter, you will require an Ubuntu 22.04 server.
You can access the code for this chapter at the following GitHub repository: https://github.com/PacktPublishing/Kubernetes-An-Enterprise-Guide-Third-Edition/tree/main/chapter11.
Introduction to dynamic admission controllers
Section titled “Introduction to dynamic admission controllers”An admission controller is a specialized webhook in Kubernetes that runs when an object is created, updated, or deleted. When one of these three events happens, the API server sends information about the object and operation to the webhook. Admission controllers can be used to either determine if an operation should happen or give the cluster operator a chance to change the object definition before it’s processed by the API server. We’re going to look at using this mechanism to both enforce security and extend the functionality of Kubernetes.
There are two ways to extend Kubernetes:
- Build a custom resource definition so that you can define your own objects and APIs.
- Implement a webhook that listens for requests from the API server and responds with the necessary information. You may recall that in Chapter 6, Integrating Authentication into Your Cluster, we explained that a custom webhook could be used to validate tokens.
Starting in Kubernetes 1.9, a webhook can be defined as a dynamic admission controller, and in 1.16, the dynamic admission controller API became Generally Available (GA).
There are two types of dynamic admission controllers, validating and mutating. Validating admission controllers verify that a new object, update, or deletion can move forward. Mutation allows a webhook to change the payload of an object’s creation, deletion, or update. This section will focus on the details of admission controllers. We’ll talk more about mutation controllers in the next chapter, Chapter 12, Node Security with GateKeeper.
The protocol is very straightforward. Once a dynamic admission controller is registered for a specific object type, the webhook is called with an HTTP POST every time an object of that type is created or edited. The webhook is then expected to return JSON, which represents whether it is allowed or not.
As of 1.16, admission.k8s.io/v1 is at GA. All examples will use the GA version of the API.
The request submitted to the webhook is made up of several sections. We’re not including an example here because of how large an Admission object can get, but we’ll use https://github.com/PacktPublishing/Kubernetes-An-Enterprise-Guide-Third-Edition/blob/main/chapter11/example_admission_request.json as an example:
- Object identifiers: The
resourceandsubResourceattributes identify the object, API, and group. If the version of the object is being upgraded, thenrequestKind,requestResource, andrequestSubResourceare specified. Additionally,namespaceandoperationare provided to provide the location of the object and whether it is aCREATE,UPDATE,DELETE, orCONNECToperation. In our example, aDeploymentresource with asubResourceofScaleis being created to scale ourDeploymentup in themy-namespacenamespace. - Submitter identifiers: The
userInfoobject identifies the user and groups of the submitter. The submitter and the user who created the original request are not always the same. For instance, if a user creates aDeployment, then theuserInfoobject won’t be for the user who created the originalDeployment; it will be for theReplicaSetcontroller’s service account because theDeploymentcreates aReplicaSetthat creates the pod. In our example, a user with theuidof admin submitted the scaling request. - Object:
objectrepresents the JSON of the object being submitted, whereasoldObjectrepresents what is being replaced if this is an update. Finally,optionsspecifies additional options for the request. In our example, the new pod with the new number of replicas after the scaling operation is submitted.
The response from the webhook will simply have two attributes, the original uid from the request and allowed, which can be true or false. For instance, to allow our scaling operation to complete:
{ "uid": "705ab4f5-6393-11e8-b7cc-42010a800002" "allowed": true}The userInfo object can create complications quickly. Since Kubernetes often uses multiple layers of controllers to create objects, it can be difficult to track usage creation based on a user who interacts with the API server.
It’s much better to authorize based on objects in Kubernetes, such as namespace labels or other objects.
A common use case is to allow developers to have a sandbox that they are administrators in, but that has very limited capacity. Instead of trying to validate the fact that a particular user doesn’t try to request too much memory, annotate a personal namespace with a limit so that the admission controller has something concrete to reference regardless of whether the user submits a pod or a Deployment. This way, the policy will check the annotation on the namespace instead of the individual user. To ensure that only the user who owns the namespace is able to create something in it, use RBAC to limit access.
One final point on generic validating webhooks: there is no way to specify a key or password. It’s an anonymous request. While, in theory, a validating webhook could be used to implement updates to your cluster, it is not recommended. For instance, you could use a validating webhook to create a ClusterRoleBinding when creating a Namespace, but that would mean that your policy check is not repeatable. It’s best to separate policy checking and workflow.
Now that we’ve covered how Kubernetes implements dynamic access controllers, we’ll look at one of the most popular options in OPA.
What is OPA and how does it work?
Section titled “What is OPA and how does it work?”OPA is a lightweight authorization engine that fits well in Kubernetes. It didn’t get its start in Kubernetes, but it’s certainly found a home there. There’s no requirement to build dynamic admission controllers in OPA, but it’s very good at it and there are extensive resources and existing policies that can be used to start your policy library.
This section provides a high-level overview of OPA and its components with the rest of the chapter getting into the details of an OPA implementation in Kubernetes.
OPA architecture
Section titled “OPA architecture”OPA comprises three components – the HTTP listener, the policy engine, and the database:

Figure 11.1 – OPA architecture
Figure 11.1: OPA architecture
The database used by OPA is in memory and ephemeral. It doesn’t persist information used to make policy decisions. On the one hand, this makes OPA very scalable since it is essentially an authorization microservice. On the other hand, this means that every instance of OPA must be maintained on its own and must be kept in sync with authoritative data:

Figure 11.2 – OPA in Kubernetes
Figure 11.2: OPA in Kubernetes
When used in Kubernetes, OPA populates its database using a sidecar, called kube-mgmt, which sets up watches on the objects you want to import into OPA. As objects are created, deleted, or changed, kube-mgmt updates the data in its OPA instance. This means that OPA is “eventually consistent” with the API server, but it won’t necessarily be a real-time representation of the objects in the API server. Since the entire etcd database is essentially being replicated over and over again, great care needs to be taken in order to refrain from replicating sensitive data, such as Secrets, in the OPA database.
Now, let’s get introduced to the OPA policy language, Rego.
Rego, the OPA policy language
Section titled “Rego, the OPA policy language”We’ll cover the details of Rego in the next section in detail. The main point to mention here is that Rego is a policy evaluation language, not a generic programming language. Rego can be difficult for developers who are used to languages such as Golang, Java, or JavaScript, which support complex logic such as iterators and loops. Rego is designed to evaluate policy and is streamlined as such. For instance, if you wanted to write code in Java to check that all the container images in a pod started with one of a list of registries, it would look something like the following:
public boolean validRegistries(List<Container> containers,List<String> allowedRegistries) { for (Container c : containers) { boolean imagesFromApprovedRegistries = false; for (String allowedRegistry : allowedRegistries) { imagesFromApprovedRegistries = imagesFromApprovedRegistries || c.getImage().startsWith(allowedRegistry); } if (! imagesFromApprovedRegistries) { return false; } } return true;}This code iterates over every container and every allowed registry to make sure that all of the images conform to the correct policy. The same code in Rego is much smaller:
invalidRegistry { ok_images = [image | startswith(input_images[j],input.parameters.registries[_]) ; image = input_images[j] ] count(ok_images) != count(input_images)}The preceding rule will evaluate to true if any of the images on the containers come from unauthorized registries. We’ll cover the details of how this code works later in the chapter. The key to understanding why this code is so much more compact is that much of the boilerplate of loops and tests is inferred in Rego. The first line generates a list of conforming images, and the second line makes sure that the number of conforming images matches the number of total images. If they don’t match, then one or more of the images must come from invalid registries. The ability to write compact policy code is what makes Rego so well suited to admission controllers.
So far, we’ve focused on generic OPA and Rego. In the early days, you would integrate Kubernetes directly into OPA using ConfigMaps to store policies; however, this proved to be really unwieldy. Microsoft developed a tool called GateKeeper, which is Kubernetes native and makes it easier to get the most out of OPA in Kubernetes. So, now, let’s get introduced to Gatekeeper.
Gatekeeper
Section titled “Gatekeeper”Thus far, everything discussed has been generic to OPA. It was mentioned at the beginning of the chapter that OPA didn’t get its start in Kubernetes. Early implementations had a sidecar that kept the OPA database in sync with the API server, but you had to manually create policies as ConfigMap objects and manually generate responses for webhooks. In 2018, Microsoft debuted Gatekeeper (https://github.com/open-policy-agent/gatekeeper) to provide a Kubernetes-native experience.
In addition to moving from ConfigMap objects to proper custom resources, Gatekeeper adds an audit function that lets you test policies against existing objects. If an object violates a policy, then a violation entry is created to track it. This way, you can get a snapshot of the existing policy violations in your cluster or know whether something was missed during Gatekeeper downtime due to an upgrade.
A major difference between Gatekeeper and generic OPA is that in Gatekeeper, OPA’s functionality is not exposed via an API anyone can call. OPA is embedded, with Gatekeeper calling OPA directly to execute policies and keep the database up to date. Decisions can only be made based on data in Kubernetes or by pulling data at evaluation time.
Deploying Gatekeeper
Section titled “Deploying Gatekeeper”The examples that will be used will assume the use of Gatekeeper instead of a generic OPA deployment.
First, create a new cluster to deploy GateKeeper into:
$ cd chapter2$ ./create-cluster.shOnce the new cluster is running, based on the directions from the Gatekeeper project, use the following command:
$ kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/deploy/gatekeeper.yamlThis launches the Gatekeeper namespace pods and creates the validating webhook. Once deployed, move on to the next section. We’ll cover the details of using Gatekeeper throughout the rest of this chapter.
Automated testing framework
Section titled “Automated testing framework”OPA has a built-in automated testing framework for your policies. This is one of the most valuable aspects of OPA. Being able to test policies consistently before deployment can save you hours of debugging time. When writing policies, have a file with the same name as your policies file, but with _test in the name. For instance, to have test cases associated with mypolicies.rego, have the test cases in mypolicies_test.rego in the same directory. Running the opa test will then run your test cases. We’ll show how to use this to debug your code in the next section.
Having covered the basics of OPA and how it is constructed, the next step is to learn how to use Rego to write policies.
Using Rego to write policies
Section titled “Using Rego to write policies”Rego is a language specifically designed for policy writing. It is different from most languages you have likely written code in. Typical authorization code will look something like the following:
//assume failureboolean allowed = false;//on certain conditions allow accessif (someCondition) { allowed = true;}//are we authorized?if (allowed) { doSomething();}Authorization code will generally default to unauthorized, with a specific condition having to happen in order to allow the final action to be authorized. Rego takes a different approach. Rego is generally written to authorize everything unless a specific set of conditions happens.
Another major difference between Rego and more general programming languages is that there are no explicit if / then / else control statements. When a line of Rego is going to make a decision, the code is interpreted as “If this line is false, stop execution.” For instance, the following code in Rego says “If the image starts with myregistry.lan/, then stop the execution of the policy and pass this check; otherwise, generate an error message”:
not startsWith(image,"myregistry.lan/")msg := sprintf("image '%v' comes from untrusted registry", [image])The same code in Java might look as follows:
if (! image.startsWith("myregistry.lan/")) { throw new Exception("image " + image + " comes from untrusted registry");}This difference between inferred control statements and explicit control statements is often the steepest part of the learning curve when learning Rego. While this can produce a steeper learning curve than other languages, Rego more than makes up for it by making it easy to test and build policies in an automated and manageable way. Another benefit of Rego is that it can be used for application-level authorizations. We’ll cover this more when we get to Istio later in the book.
OPA can be used to automate the testing of policies. This is incredibly important when writing code that the security of your cluster relies upon. Automating your testing will help speed up your development and will increase your security by catching any bugs introduced into previously working code by means of new working code. Next, let’s work through the life cycle of writing an OPA policy, testing it, and deploying it to our cluster.
Developing an OPA policy
Section titled “Developing an OPA policy”A common example of using OPA is to limit which registries a pod can come from. This is a common security measure in clusters to help restrict which pods can run on a cluster. For instance, we’ve mentioned Bitcoin miners a few times. If the cluster won’t accept pods except from your own internal registry, then that’s one more step that needs to be taken for a bad actor to abuse your cluster. First, let’s write our policy, taken from the OPA documentation website (https://www.openpolicyagent.org/docs/latest/kubernetes-introduction/):
package k8sallowedregistriesinvalidRegistry { input_images[image] not startswith(image, "quay.io/")}input_images[image] { image := input.review.object.spec.containers[_].image}input_images[image] { image := input.review.object.spec.template.spec.containers[_].image}The first line in this code declares the package our policy is in. Everything is stored in OPA in a package, both data and policies.
Packages in OPA are like directories on a filesystem. When you place a policy in a package, everything is relative to that package. In this case, our policy is in the k8sallowedregistries package.
The next section defines a rule. This rule ultimately will be undefined if our pod has an image that comes from quay.io. If the pod doesn’t have an image from quay.io, the rule will return true, signifying that the registry is invalid. Gatekeeper will interpret this as a failure and return false to the API server when the pod is evaluated during a dynamic admission review.
The next two rules look very similar. The first of the input_images rules says “Evaluate the calling rule against every container in the object’s spec.container,” matching pod objects directly submitted to the API server and extracting all the image values for each container. The second input_images rule states “Evaluate the calling rule against every container in the object’s spec.template.spec.containers ” to short circuit Deployment objects and StatefulSets.
Finally, we add the rule that Gatekeeper requires to notify the API server of a failed evaluation:
violation[{"msg": msg, "details": {}}] { invalidRegistry msg := "Invalid registry"}This rule will return an empty msg if the registry is valid. It’s a good idea to break up your code into code that makes policy decisions and code that responds with feedback. This makes it easier to test, which we’ll do next.
Testing an OPA policy
Section titled “Testing an OPA policy”Once we have written our policy, we want to set up an automated test. Just as with testing any other code, it’s important that your test cases cover both expected and unexpected input. It’s also important to test both positive and negative outcomes. It’s not enough to corroborate that our policy allowed a correct registry; we also need to make sure it stops an invalid one. Here are eight test cases for our code:
package k8sallowedregistriestest_deployment_registry_allowed { not invalidRegistry with input as {"apiVersion"...}test_deployment_registry_not_allowed { invalidRegistry with input as {"apiVersion"...}test_pod_registry_allowed { not invalidRegistry with input as {"apiVersion"...}test_pod_registry_not_allowed { invalidRegistry with input as {"apiVersion"...}test_cronjob_registry_allowed { not invalidRegistry with input as {"apiVersion"...}test_cronjob_registry_not_allowed { invalidRegistry with input as {"apiVersion"...}test_error_message_not_allowed { control := {"msg":"Invalid registry","details":{}} result = violation with input as {"apiVersion":"admissi… result[_] == control}test_error_message_allowed { result = violation with input as {"apiVersion":"admissi… result == set()}There are eight tests in total: two tests to make sure that the proper error message is returned when there’s an issue, and six tests covering two use cases for three input types. We’re testing simple pod definitions, Deployment, and CronJob. To validate success or failure as expected, we have included definitions that have image attributes that include docker.io and quay.io for each input type. The code is abbreviated for print but can be downloaded from https://github.com/PacktPublishing/Kubernetes-An-Enterprise-Guide-Third-Edition/tree/main/chapter11/simple-opa-policy/rego/.
To run the tests, first, install the OPA command-line executable as per the OPA website: https://www.openpolicyagent.org/docs/latest/#running-opa. Once it has been downloaded, go to the simple-opa-policy/rego directory and run the tests:
$ opa test .data.kubernetes.admission.test_cronjob_registry_not_allowed: FAIL (248ns)--------------------------------------------------------------PASS: 7/8FAIL: 1/8Seven of the tests passed, but test_cronjob_registry_not_allowed failed. The CronJob submitted as input should not be allowed because its image uses docker.io. The reason it snuck through was that CronJob objects follow a different pattern to Pods and Deployments, so our two input_image rules won’t load any of the container objects from the CronJob. The good news is that when the CronJob ultimately submits the pod, Gatekeeper will not validate it, thereby preventing it from running. The bad news is that no one will know this until the pod is supposed to be run. Making sure we pick up CronJob objects in addition to our other objects with containers in them will make it much easier to debug because the CronJob won’t be accepted.
To get all tests passing, add a new input_container rule to the limitregistries.rego file in the GitHub repo that will match the container used by a CronJob:
input_images[image] { image := input.review.object.spec.jobTemplate.spec.template.spec.containers[_].image}Now, running the tests will show that everything passes:
$ opa test .PASS: 8/8With a policy that has been tested, the next step is to integrate the policy into Gatekeeper.
Deploying policies to Gatekeeper
Section titled “Deploying policies to Gatekeeper”The policies we’ve created need to be deployed to Gatekeeper, which provides Kubernetes custom resources that policies need to be loaded into. The first custom resource is ConstraintTemplate, which is where the Rego code for our policy is stored. This object lets us specify parameters in relation to our policy enforcement, and we’ll cover this next. To keep things simple, create a template with no parameters:
apiVersion: templates.gatekeeper.sh/v1beta1kind: ConstraintTemplatemetadata: name: k8sallowedregistriesspec: crd: spec: names: kind: K8sAllowedRegistries validation: {} targets: - target: admission.k8s.gatekeeper.sh rego: | package k8sallowedregistries . . .The entire source code for this template is available at https://github.com/PacktPublishing/Kubernetes-An-Enterprise-Guide-Third-Edition/blob/main/chapter11/simple-opa-policy/yaml/gatekeeper-policy-template.yaml.
Once created, the next step is to apply the policy by creating a constraint based on the template. Constraints are objects in Kubernetes based on the configuration of ConstraintTemplate. Notice that our template defines a custom resource definition. This gets added to the constraints.gatekeeper.sh API group. If you look at the list of CRDs on your cluster, you’ll see k8sallowedregistries listed:

Figure 11.3 – CRD created by ConstraintTemplate
Figure 11.3: CRD created by ConstraintTemplate
Creating the constraint means creating an instance of the object defined in the template.
To keep from causing too much havoc in our cluster, we’re going to restrict this policy to the testpolicy namespace:
apiVersion: constraints.gatekeeper.sh/v1beta1kind: K8sAllowedRegistriesmetadata: name: restrict-openunison-registriesspec: match: kinds: - apiGroups: [""] kinds: ["Pod"] - apiGroups: ["apps"] kinds: - StatefulSet - Deployment - apiGroups: ["batch"] kinds: - CronJob namespaces: ["testpolicy"]The constraint limits the policy we wrote to just Deployment, CronJob, and Pod objects in the testpolicy namespace. Once our policy is created, if we try to create a pod in the testpolicy namespace that comes from docker.io, it will fail because the image comes from docker.io, not quay.io, not quay.io. First, let’s create our testpolicy namespace and an example Deployment that will violate this policy:
$ chapter11/simple-opa-policy/yaml$ kubectl create ns testpolicy$ kubectl create deployment nginx-prepolicy --image=docker.io/nginx/nginx-ingress -n testpolicy$ kubectl create -f ./gatekeeper-policy.yaml$ kubectl create deployment nginx-withpolicy --image=docker.io/nginx/nginx-ingress -n testpolicyerror: failed to create deployment: admission webhook "validation.gatekeeper.sh" denied the request: [restrict-openunison-registries] Invalid registryThe last line tried to create a new Deployment that references docker.io instead of quay.io, which failed because our policy blocked it. But we also created a Deployment that violates this rule before deploying our policy, which means that our admission controller never received a create command. This is one feature of Gatekeeper over generic OPA that is very powerful: Gatekeeper audits your existing infrastructure against new policies. This way, you can find offending deployments quickly.
Next, look at the policy object. You will see that there are several violations in the status section of the object:
$ kubectl get k8sallowedregistries.constraints.gatekeeper.sh restrict-openunison-registries -o json | jq -r '.status.violations'[ { "enforcementAction": "deny", "group": "", "kind": "Pod", "message": "Invalid registry", "name": "nginx-prepolicy-8bd5cbfc9-szzs4", "namespace": "testpolicy", "version": "v1" }, { "enforcementAction": "deny", "group": "apps", "kind": "Deployment", "message": "Invalid registry", "name": "nginx-prepolicy", "namespace": "testpolicy", "version": "v1" }]Having deployed your first Gatekeeper policy, you may quickly notice it has a few issues. The first is that the registry is hardcoded. This means that we’d need to replicate our code for every change of registry. It’s also not flexible for the namespace. As an example, Tremolo Security’s images are across multiple github.io registries, so instead of limiting a specific registry server, we may want flexibility for each namespace and to allow multiple registries. Next, we’ll update our policies to provide this flexibility.
Building dynamic policies
Section titled “Building dynamic policies”Our current registry policy is limiting. It is static and only supports a single registry. Both Rego and Gatekeeper provide functionality to build a dynamic policy that can be reused in our cluster and configured based on individual namespace requirements. This gives us one code base to work from and debug instead of having to maintain repetitive code. The code we’re going to use is at https://github.com/PacktPublishing/Kubernetes-An-Enterprise-Guide-Third-Edition/tree/main/chapter11/parameter-opa-policy.
When inspecting rego/limitregistries.rego, the main difference between the code in parameter-opa-policy and simple-opa-policy comes down to the invalidRegistry rule:
invalidRegistry { ok_images = [image | startswith(input_images[i],input.parameters.registries[_]) ; image = input_images[i] ] count(ok_images) != count(input_images)}The goal of the first line of the rule is to determine which images come from approved registries using a comprehension. Comprehensions provide a way to build out sets, arrays, and objects based on some logic. In this case, we want to only add images to the ok_images array that start with any of the allowed registries from input.parameters.registries.
To read a comprehension, start with the type of brace. Ours starts with a square bracket, so the result will be an array. Objects and sets can also be generated. The word between the open bracket and the pipe character (|) is called the head and this is the variable that will be added to our array if the right conditions are met. Everything to the right of the pipe character (|) is a set of rules used to determine what image should be and if it should have a value at all. If any of the statements in the rule resolve to undefined or false, the execution exits for that iteration.
The first rule of our comprehension is where most of the work is done. The startswith function is used to determine whether each of our images starts with the correct registry name. Instead of passing two strings to the function, we instead pass arrays. The first array has a variable we haven’t declared yet, i, and the other uses an underscore (_) where the index would usually be. The i is interpreted by Rego as “ Do this for each value in the array, incrementing by 1, and let it be referenced throughout the comprehension.” The underscore is shorthand in Rego for “ Do this for all values.” Since we specified two arrays, every combination of the two arrays will be used as input to the startswith function.
That means that if there are two containers and three potential pre-approved registries, then startswith will be called six times. When any of the combinations return true from startswith, the next rule is executed. That sets the image variable to input_image with index i, which then means that the image is added to ok_images. The same code in Java would look something like the following:
ArrayList<String> okImages = new ArrayList<String>();for (int i=0;i<inputImages.length;i++) { for (int j=0;j<registries.length;j++) { if (inputImages[i].startsWith(registries[j])) { okImages.add(inputImages[i]); } }}One line of Rego eliminated seven lines of mostly boilerplate code.
The second line of the rule compares the number of entries in the ok_images array with the number of known container images. If they are equal, we know that every container contains a valid image.
With our updated Rego rules for supporting multiple registries, the next step is to deploy a new policy template (if you haven’t done so already, delete the old k8sallowedregistries ConstraintTemplate and restrict-openunison-registries K8sAllowedRegistries):
$ kubectl delete -f ./gatekeeper-policy.yaml k8sallowedregistries.constraints.gatekeeper.sh "restrict-openunison-registries" deleted$ kubectl delete -f ./gatekeeper-policy-template.yaml constrainttemplate.templates.gatekeeper.sh "k8sallowedregistries" deletedHere’s our updated ConstraintTemplate:
apiVersion: templates.gatekeeper.sh/v1beta1kind: ConstraintTemplatemetadata: name: k8sallowedregistriesspec: crd: spec: names: kind: K8sAllowedRegistries validation: openAPIV3Schema: properties: registries: type: array items: string targets: - target: admission.k8s.gatekeeper.sh rego: | package k8sallowedregistries . . .Beyond including our new rules, the highlighted section shows that we added a schema to our template. This will allow for the template to be reused with specific parameters. This schema goes into the CustomResourceDefinition that will be created and is used to validate input for the K8sAllowedRegistries objects we’ll create in order to enforce our pre-authorized registry lists. Create this new policy definition:
$ cd chapter11/parameter-opa-policy/yaml/$ kubectl create -f gatekeeper-policy-template.yamlFinally, let’s create our policy for the testpolicy namespace. Since the only containers that are running in this namespace should come from NGINX’s docker.io registry, we’ll limit all pods to docker.io/nginx/ using the following policy:
apiVersion: constraints.gatekeeper.sh/v1beta1kind: K8sAllowedRegistriesmetadata: name: restrict-openunison-registriesspec: match: kinds: - apiGroups: [""] kinds: ["Pod"] - apiGroups: ["apps"] kinds: - StatefulSet - Deployment - apiGroups: ["batch"] kinds: - CronJob namespaces: ["testpolicy"] parameters: registries: ["docker.io/nginx/"]Unlike our previous version, this policy specifies which registries are valid instead of embedding the policy data directly into our Rego. With our policies in place, let’s try to run the BusyBox container in the testpolicy namespace to get a shell:
$ kubectl create -f ./gatekeeper-policy.yaml$ kubectl run tmp-shell --rm -i --tty --image docker.io/busybox -n testpolicy -- /bin/bashError from server (Forbidden): admission webhook "validation.gatekeeper.sh" denied the request: [restrict-openunison-registries] Invalid registry$ kubectl create deployment nginx-withpolicy --image=docker.io/nginx/nginx-ingress -n testpolicydeployment.apps/nginx-withpolicy createdIn the above example, we were able to stop the BusyBox container from being deployed, but the NGINX Deployment was created because we were able to restrict the specific container registry on docker.io.
Using this generic policy template, we can restrict which registries the namespaces are able to pull from. As an example, in a multi-tenant environment, you may want to restrict all pods to the owner’s own registry. If a namespace is being used for a commercial product, you can stipulate that only that vendor’s containers can run in it. Before moving on to other use cases, it’s important to understand how to debug your code and handle Rego’s quirks.
Debugging Rego
Section titled “Debugging Rego”Debugging Rego can be challenging. Unlike more generic programming languages such as Java or Go, there’s no way to step through code in a debugger. Take the example of the generic policy we just wrote for checking registries. All the work was done in a single line of code. Stepping through it wouldn’t do much good.
To make Rego easier to debug, the OPA project provides a trace of all failed tests when verbose output is set on the command line. This is another great reason to use OPA’s built-in testing tools.
To make better use of this trace, Rego has a function called trace that accepts a string. Combining this function with sprintf lets you more easily track where your code is not working as expected. In the chapter11/parameter-opa-policy-fail/rego directory, there’s a test that will fail. There is also an invalidRegistry rule with multiple trace options added:
invalidRegistry { trace(sprintf("input_images : %v",[input_images])) ok_images = [image | trace(sprintf("image %v",[input_images[j]])) startswith(input_images[j],input.parameters.registries[_]) ; image = input_images[j] ] trace(sprintf("ok_images %v",[ok_images])) trace(sprintf("ok_images size %v / input_images size %v",[count(ok_images),count(input_images)])) count(ok_images) != count(input_images)}When the test is run, OPA will output a detailed trace of every comparison and code path. Wherever it encounters the trace function, a “note” is added to the trace. This is the equivalent of adding print statements in your code to debug. The output of the OPA trace is very verbose, and far too much text to include in print. Running opa test . -v in this directory will give you the full trace you can use to debug your code.
Using existing policies
Section titled “Using existing policies”Before moving into more advanced use cases for OPA and Gatekeeper, it’s important to understand the implications of how OPA is built and used. If you inspect the code we worked through in the previous section, you might notice that we aren’t checking for an initContainer. We’re only looking for the primary containers. An initContainer is a special container that is run before the containers listed in a pod are expected to end. They’re often used to prepare the filesystem of a volume mount and for other “initial” tasks that should be performed before the containers of a pod have run. If a bad actor tried to launch a pod with an initContainer that pulls in a Bitcoin miner (or worse), our policy wouldn’t stop it.
It’s important to be very detailed in the design and implementation of policies. One of the ways to make sure you’re not missing something when building policies is to use policies that already exist and have been tested. The Gatekeeper project maintains several libraries of pre-tested policies and how to use them in its GitHub repo at https://github.com/open-policy-agent/gatekeeper-library. Before attempting to build one of your own policies, see whether one already exists there first.
This section provided an overview of Rego and how it works in policy evaluation. It didn’t cover everything, but should give you a good point of reference for working with Rego’s documentation. Next, we’ll learn how to build policies that rely on data from outside our request, such as other objects in our cluster.
Enforcing Ingress policies
Section titled “Enforcing Ingress policies”So far in this chapter, we’ve built policies that are self-contained. When checking whether an image is coming from a pre-authorized registry, the only data we needed was from the policy and the containers. This is often not enough information to make a policy decision. In this section, we’ll work on building a policy that relies on other objects in your cluster to make policy decisions.
Before diving into the implementation, let’s talk about the use case. It’s common to limit which namespaces can have Ingress objects. If a namespace hosts a workload that doesn’t require any inbound access, why allow an Ingress object at all? You may think you can enforce this using RBAC by limiting what tenants are allowed to deploy using a Role and RoleBinding, but this has some limitations:
- The
adminand editClusterRolesare default aggregateClusterRoles, so you would need to create a newClusterRolethat enumerates all objects exceptIngressthat you want your namespace admin to be able to create. - If your new
ClusterRoleincludedRoleBindings, your namespace owner could just grant themselvesIngresscreation.
Using an admission controller with an annotation or a label is a good approach to enforcing if the namespace can have an Ingress in it. The Namespace object is cluster-scoped, so an admin won’t be able to elevate their privileges in the namespace and add the label.
In our next example, we’ll write a policy that only allows Ingress objects in namespaces that have the correct label. The pseudo-code would look something like this:
if (! hasIngressAllowedLabel(input.review.object.metdata.namespace)) { generate error;}The hard part here is understanding if the namespace has a label. Kubernetes has an API, which you could query, but that would mean either embedding a secret into the policy so it can talk to the API server or allowing anonymous access. Neither of those options is a good idea. Another issue with querying the API server is that it’s difficult to automate testing since you are now reliant on an API server being available wherever you run your tests.
We discussed earlier that OPA can replicate data from the API server in its own database. Gatekeeper uses this functionality to create a cache of objects that can be tested against. Once this cache is populated, we can replicate it locally to provide test data for our policy testing.
Enabling the Gatekeeper cache
Section titled “Enabling the Gatekeeper cache”The Gatekeeper cache is enabled by creating a Config object in the gatekeeper-system namespace. Add this configuration to your cluster:
apiVersion: config.gatekeeper.sh/v1alpha1kind: Configmetadata: name: config namespace: "gatekeeper-system"spec: sync: syncOnly: - group: "" version: "v1" kind: "Namespace"$ cd chapter11/enforce-ingress/yaml/$ kubectl create -f ./config.yamlThis will begin replicating Namespace objects in Gatekeeper’s internal OPA database. Let’s create a Namespace with a label allowing Ingress objects and without a label allowing Ingress objects:
apiVersion: v1kind: Namespacemetadata: name: ns-with-ingress labels: allowingress: "true"spec: {}---apiVersion: v1kind: Namespacemetadata: name: ns-without-ingressspec: {}After a moment, the data should be in the OPA database and ready to query.
The Gatekeeper service account has read access to everything in your cluster with its default installation. This includes secret objects. Be careful what you replicate in Gatekeeper’s cache as there are no security controls from inside a Rego policy. Your policy could very easily log secret object data if you are not careful. Also, make sure to control who has access to the gatekeeper-system namespace. Anyone who gets hold of the service account’s token can use it to read any data in your cluster.
Now that we have Gatekeeper set up and ready to start enforcing policies, how do we test policies? We could test them directly against a cluster, but that will slow down our development cycle. Next, we’ll see how to mock test data so that we can automate our testing outside of a Kubernetes cluster.
Mocking up test data
Section titled “Mocking up test data”In order to automate the testing of our policy, we need to create test data. In the previous examples, we used data injected into the input variable. Cache data is stored in the data variable. Specifically, in order to access our namespace labels, we need to access data.inventory.cluster["v1"].Namespace["ns-with-ingress"].metadata.labels. This is the standard way for you to query cluster data from Rego in Gatekeeper. If you want to query objects inside of a namespace, it would instead look like data.inventory.namespace["myns"]["v1"]["ConfigMaps"]["myconfigmap"]. Just as we did with the input, we can inject a mocked-up version of this data by creating a data object. Here’s what our JSON will look like:
{ "cluster": { "v1": { "Namespace": { "ns-with-ingress": { "metadata": { "labels": { "allowingress": "true" } } }, "ns-without-ingress": { "metadata": { }}}}}}When you look at chapter11/enforce-ingress/rego/enforceingress_test.rego, you’ll see the tests have with input as {…} with data as {…} with the preceding document as our control data. This lets us test our policies with data that would exist in GateKeeper without having to deploy our code in a cluster.
Building and deploying our policy
Section titled “Building and deploying our policy”Just as before, we’ve written test cases prior to writing our policy. Next, we’ll examine our policy:
package k8senforceingressviolation[{"msg":msg,"details":{}}] { missingIngressLabel msg := "Missing label allowingress: \"true\""}missingIngressLabel {data.inventory.cluster["v1"].Namespace[input.review.object.metadata.namespace].metadata.labels["allowingress"] != "true"}missingIngressLabel { not data.inventory.cluster["v1"].Namespace[input.review.object.metadata.namespace].metadata.labels["allowingress"]}This code should look familiar. It follows a similar pattern as our earlier policies. The first rule, violation, is the standard reporting rule for Gatekeeper. The second and third rules have the same name but different logic. This is because Rego evaluates all of the statements in a rule as an AND, so for the rule to be true, all of the statements need to be true. If we only had the first missingIngressLabel rule, which checks if the allowingress label is true, then Ingress objects without this label at all would break the rule and so bypass our requirement. We could have a rule that requires that the label be set, but that would lead to a bad user experience. It would be better to set up our policy so that it will fail if the label isn’t true OR the label isn’t set at all.
To set up the logic of “if the label’s value is not true or the label is not present,” we need to have two rules with the same name. One rule checks for the label’s value, and the other validates if the label is there at all. Rego will execute both missingIngressLabel rules and, as long as one passes, execution will continue. In our case, if the namespace the Ingress object is created in doesn’t have the correct value of allowingress, or doesn’t have the label allowingress at all, the violation rule will complete, returning an error to the user.
This is a key difference between Rego and other languages. Rego isn’t executed in sequence the way Java, Go, or JavaScript is. It’s a policy language that’s evaluated, so the execution path is different. When writing Rego, it’s important to remember you’re not working with a typical programming language.
To deploy, add chapter11/enforce-ingress/yaml/gatekeeper-policy-template.yaml and chapter11/enforce-ingress/yaml/gatekeeper-policy.yaml to your cluster.
To test, we’ll try creating an Ingress object in the ns-without-ingress namespace:
$ kubectl create ingress test --rule="foo.com/bar=svc1:8080,tls=my-cert" -n ns-without-ingresserror: failed to create ingress: admission webhook "validation.gatekeeper.sh" denied the request: [require-ingress-label] Missing label allowingress: "true"You can see that our policy blocked the Ingress object’s creation. Next, we’ll try to create the same Ingress object but in the ns-with-ingress namespace, which has the correct label:
$ kubectl create ingress test --rule="foo.com/bar=svc1:8080,tls=my-cert" -n ns-with-ingressingress.networking.k8s.io/test createdThis time, our policy allowed the Ingress object to be created!
Most of this chapter has been spent writing policies. Next, we’ll cover how to provide sane defaults to your objects using mutating webhooks.
Mutating objects and default values
Section titled “Mutating objects and default values”Until this point, everything we have discussed has been about how to use Gatekeeper to enforce a policy. Kubernetes has another feature called mutating admission webhooks that allows a webhook to change, or mutate, an object before the API server processes it and runs validating admission controllers.
A common usage of a mutating webhook is to explicitly set security context information on pods that don’t have it set. For instance, if you create a pod with no spec.securityContext.runAsUser, then the pod will run as the user the Docker container was built to run using the USER directive (or root by default) when it was built. This is insecure since it means you could be running as root, especially if the container in question is from Docker Hub. While you can have a policy that blocks running as root, you could also have a mutating webhook that will set a default user ID if it’s not specified to make it a default. This makes for a better developer experience because, now, as a developer, I don’t have to worry about which user my container was built to run as so long as it was designed to work with any user.
This brings up a common question of defaults versus explicit configuration. There are two schools of thought. The first is that you should provide sane defaults wherever possible to minimize what developers have to know to get a typical workload running. This creates consistency and makes it easier to spot outliers. The other school of thought requires explicit configuration of security contexts so that it’s known looking at a glance what the workload expects. This can make auditing easier, especially if paired with GitOps to manage your manifests, but creates quite a bit of repetitive YAML.
I’m personally a fan of sane defaults. The vast majority of workloads will not require any privilege and should be treated as such. It doesn’t mean you don’t still need enforcement, just that it’s a better experience for your developers. It also makes it easier to make global changes. Want to change the default user ID or security context? You make the change in your mutating webhook instead of across tens, hundreds, or even thousands of manifests. Most of Kubernetes is built this way. You don’t create pod objects directly; you create Deployments and StatefulSets with controllers that create pods. Going back to our discussions on RBAC, aggregate roles work this way too. Instead of creating a massive ClusterRole for namespace administrators, Kubernetes uses a controller to generate the ClusterRole dynamically based on label selectors, making it easier to maintain. In my experience, this example should be applied to security defaults as well.
Gatekeeper’s mutation isn’t built on Rego the way its validation policies are. While you can write mutating webhooks in Rego, and I can say this from experience, it’s not well suited to it. What makes Rego a great policy definition language also makes it very hard to build mutations.
Now that we know what mutations are useful and that we can use Gatekeeper, let’s build a mutation that will configure all containers to run as a default user if none is specified.
First, let’s deploy something that we can test our mutations:
$ kubectl create ns test-mutations$ kubectl create deployment test-nginx --image=ghcr.io/openunison/openunison-k8s-html:latest -n test-mutationsNow, we can deploy the policy in chapter11/defaultUser/addDefaultUser.yaml:
apiVersion: mutations.gatekeeper.sh/v1kind: Assignmetadata: name: default-userspec: applyTo: - groups: [""] kinds: ["Pod"] versions: ["v1"] match: scope: Namespaced excludedNamespaces: - kube-system location: "spec.securityContext.runAsUser" parameters: assign: value: 70391 pathTests: - subPath: "spec.securityContext.runAsUser" condition: MustNotExistLet’s walk through this mutation. The first part of the spec, applyTo, tells Gatekeeper what objects you want this mutation to act on. For us, we want it to work on all pods.
The next section, match, gives you the chance to specify conditions on which pods we want the mutation to apply to. In our case, we’re applying to all of them except in the kube-system namespace. In general, I tend to avoid making changes to anything in the kube-system namespace because it’s the domain of whoever is managing your clusters.
Making changes there can have permanent impacts on your cluster. In addition to specifying which namespaces you don’t want to apply your mutation to, you can also specify additional conditions:
kind– What kind of object to match onlabelSelectors– Labels on the object that must matchnamespaces– List of namespaces to apply the mutation policy tonamespaceSelector– Labels on the container namespaces
We’ll talk more about label matching in Chapter 12, Node Security with GateKeeper.
After defining how to match objects to mutate, we specify what mutation to perform. For us, we want to set spec.securityContext.runAsUser to a randomly chosen user ID if one isn’t specified. The last part, pathTests, is what lets us set this value if the spec.securityContext.runAsUser isn’t already set.
Once you’ve applied your mutation policy, verify that the test pod isn’t running as a specific user:
$ kubectl get pods -l app=test-nginx -o jsonpath='{.items[0].spec.securityContext}' -n test-mutations{}Now, delete the pod and check again:
$ kubectl delete pods -l app=test-nginx -n test-mutationspod " test-nginx-f6c8578fc-qkd5h" deleted$ kubectl get pods -l app=test-nginx -o jsonpath='{.items[0].spec.securityContext}' -n test-mutations{"runAsUser":70391}Our pod is now running as user 70391! Now, let’s edit our deployment so that the user is set the user identity:
$ kubectl patch deployment test-nginx --patch '{"spec":{"template":{"spec":{"securityContext":{"runAsUser":19307}}}}}' -n test-mutationsdeployment.apps/test-nginx patched$ kubectl get pods -l app=test-nginx -o jsonpath='{.items[0].spec.securityContext}' -n test-mutations{"runAsUser":19307}Our mutation didn’t apply because we already had a user specified in our Deployment object.
One last note on setting values: you’ll often find that you want to set a value for an object in a list. For instance, you may want to create a policy that will set any container as unprivileged unless specifically set to be privileged. In chapter11/defaultUser/yaml/setUnprivileged.yaml, our location (and subPath) have changed:
location: "spec.containers[image:*].securityContext.privileged"This reads as “Match all objects in the list spec.containers that have an attribute called image.” Since every container must have an image, this will match all containers. Apply this object and test it out again on the test pod:
$ kubectl get pods -l app=test-nginx -o jsonpath='{.items[0].spec.containers[0].securityContext}' -n test-mutations$ kubectl delete pods -l app=test-nginx -n test-mutationspod " test-nginx-ccf9bfcd-wt97v" deleted$ kubectl get pods -l app=test-nginx -o jsonpath='{.items[0].spec.containers[0].securityContext}' -n test-mutations{"privileged":false}Now our pod is marked as unprivileged!
In this section, we looked at how you can set defaults using Gatekeeper’s built-in mutation support. We discussed the benefits of mutating webhooks that set defaults, enabled Gatekeeper’s support for mutations, and built policies that set a default user identity and disable privileged containers. Using what you’ve learned in this section, you can use Gatekeeper not only to enforce your policies but also to set sane defaults to make compliance easier for your developers. Using GateKeeper for policy management is great, but it does require additional skills and the management of an additional system. Next, we’ll learn how to create policies with alternatives to Rego or using Kubernetes’ new built-in policy engine.
Creating policies without Rego
Section titled “Creating policies without Rego”Rego is a very powerful way to build complex policies that are then implemented by the GateKeeper project. That power comes with a steep learning curve and complexity. It may not be the right choice for you or your clusters. It isn’t the only way to implement an admission controller. We’re not going to go into too many details, as these other projects all have their own capabilities that are worth exploring and I won’t be able to do them justice in one section.
The two most common alternatives to GateKeeper are:
- Kyverno: Kverno is a specialized policy engine for Kubernetes. It’s not designed as a generic authorization engine the way OPA is so it can make assumptions that provide a simpler experience for building Kubernetes policies (https://kyverno.io/).
- jsPolicy: The jsPolicy project allows you to build your policies in JavaScript or TypeScript instead of a domain-specific language (DSL) like Rego. The idea is that many of the quirks that come from Rego being a policy language, not a programming language, are eliminated by using a common language like JavaScript (https://github.com/loft-sh/jspolicy).
These projects both have their own strengths and I encourage you to evaluate them for your use cases. If your policies are straightforward and don’t require the power of one of these engines, you can also look at Kubernetes’ new built-in capabilities, which is what we’ll cover next.
Using Kubernetes’ validating admission policies
Section titled “Using Kubernetes’ validating admission policies”In 1.28 Kubernetes, validating admission policies went into beta, which allows you to create simpler policies without an external admission controller. For simpler policies, this eliminates a component that needs to be deployed. We’re not going to dive too deeply into building admission policies, but we wanted to give you an overview so that you have it as an option.
From a policy development perspective, the biggest difference between using Gatekeeper and validating admission policies is that while Gatekeeper uses Rego, validating admission policies use the Common Expression Language (CEL). CEL is not a Turing Complete language, which means that it isn’t as expressive and capable as JavaScript but is easier to secure. CEL is being integrated into multiple layers of Kubernetes. It’s being used to provide more expressive validation for custom resource definitions and is also being integrated into the new authentication configuration options that are being developed. You can learn more about CEL at https://github.com/google/cel-spec.
From a capability perspective, you can use CEL to validate any of the data inside of the object to be created. There are two components to build a validating admission policy:
ValidatingAdmissionPolicy: This is the object that describes the policy and the expressions to run as part of that policy. This is similar toConstraintTemplatefrom Gatekeeper.ValidatingAdmissionPolicyBinding: This is how Kubernetes knows when to apply ourValidatingAdmissionPolicy.
To implement our example from above where we want to limit Ingress objects to namespaces with a specific label, first, we’d create the ValidatingAdmissionPolicy (chapter11/enforce-ingress-vap/vap-ingress.yaml):
apiVersion: admissionregistration.k8s.io/v1beta1kind: ValidatingAdmissionPolicymetadata: name: "vap-ingress"spec: failurePolicy: Fail matchConstraints: resourceRules: - apiGroups: ["networking.k8s.io"] apiVersions: ["v1"] operations: ["CREATE", "UPDATE"] resources: ["ingresses"] validations: - expression: |- namespaceObject.metadata.labels.allowingress == "true"The above policy will fail if the namespace that the Ingress is added to doesn’t have the label allowingress with a value of true. Next, we need to tell Kubernetes to bind our policy. We want this to apply to all namespaces, but similar to a policy implementation for Gatekeeper, we can specify specific namespaces or namespace labels. We do this using a ValidatingAdmissionPolicy (chapter11/enforce-ingress-vap/vap-binding-ingress.yaml):
apiVersion: admissionregistration.k8s.io/v1beta1kind: ValidatingAdmissionPolicyBindingmetadata: name: "vap-binding-ingress"spec: policyName: "vap-ingress" validationActions: [Deny]This binding will bind our policy to all namespaces, and on failure, deny the request. We could also warn the user or just audit the event. In our case, we want the request to fail. With these two objects created, we can try to create Ingress objects again:
$ kubectl create ingress test --rule="foo.com/bar=svc1:8080,tls=my-cert" -n ns-without-ingresserror: failed to create ingress: ingresses.networking.k8s.io "test" is forbidden: ValidatingAdmissionPolicy 'vap-ingress' with binding 'vap-binding-ingress' denied request: expression 'namespaceObject.metadata.labels.allowingress == "true"' resulted in error: no such key: allowingress$ kubectl create ingress test --rule="foo.com/bar=svc1:8080,tls=my-cert" -n ns-with-ingressingress.networking.k8s.io/test createdJust as with our Gatekeeper examples, we see that we’re able to deny the creation of an Ingress rule if our namespace doesn’t have the appropriate label.
The addition of validating access policies to Kubernetes adds a powerful tool, but it does have its limits. It’s tempting to say we’ll use validating access policies for simple use cases, and Gatekeeper for more complex ones, but there are other things to keep in mind beyond the implementation complexity. For one, how are you monitoring failures? If you use both solutions, then even though you may have some simpler rule implementations, you’ll need to audit both solutions, which will create more work.
While we introduced validating access policies so you’re aware of their capability, we’re going to continue to focus on OPA and Gatekeeper in future chapters. In the next chapter, we’re going to apply what we’ve learned about OPA and Gatekeeper to help secure Kubernetes nodes.
Summary
Section titled “Summary”In this chapter, we explored how to use Gatekeeper as a dynamic admission controller to provide additional authorization policies on top of Kubernetes’ built-in RBAC capabilities. We looked at how Gatekeeper and OPA are architected. Then, we learned how to build, deploy, and test policies in Rego. Finally, you were shown how to use Gatekeeper’s built-in mutation support to create default configuration options in pods.
Extending Kubernetes’ policies leads to a stronger security profile in your clusters and provides greater confidence in the integrity of the workloads you are running.
Using Gatekeeper can also help catch previously missed policy violations through its application of continuous audits. Using these capabilities will provide a stronger foundation for your cluster.
This chapter focused on whether or not to launch a pod based on our specific policies. In the next chapter, we’ll learn how to protect your nodes from the processes running in those pods.
Questions
Section titled “Questions”- Are OPA and Gatekeeper the same thing?
- Yes 2. No
- How is Rego code stored in Gatekeeper?
- It is stored as
ConfigMapobjects that are watched. 2. Rego has to be mounted to the pod. 3. Rego needs to be stored as secret objects. 4. Rego is saved as aConstraintTemplate.
- It is stored as
- How do you test Rego policies?
- In production 2. Using an automated framework built directly into OPA 3. By first compiling to WebAssembly
- In Rego, how do you write a
forloop?- You don’t need to; Rego will identify iterative steps.
2. By using the
for allsyntax. 3. By initializing counters in a loop. 4. There are no loops in Rego.
- You don’t need to; Rego will identify iterative steps.
2. By using the
- What is the best way to debug Rego policies?
- Use an IDE to attach to the Gatekeeper container in a cluster.
2. In production.
3. Add trace functions to your code and run the
opa testcommand with-vto see execution traces. 4. IncludeSystem.outstatements.
- Use an IDE to attach to the Gatekeeper container in a cluster.
2. In production.
3. Add trace functions to your code and run the
- Constraints all need to be hardcoded.
- True 2. False
- Gatekeeper can replace pod security policies.
- True 2. False
Answers
Section titled “Answers”- b – No, Gatekeeper is a Kubernetes-native policy engine built on OPA.
- d – Rego is saved as a
ConstraintTemplate - b – Please don’t test in production!
- a – Everything is built on policy, not iterative control loops.
- c – Add trace functions to your code and run the
opa testcommand with-vto see execution traces - b – False. You can have variable constraints.
- a – True, and we’ll cover that in the next chapter!
Join our book’s Discord space
Section titled “Join our book’s Discord space”Join the book’s Discord workspace for a monthly Ask Me Anything session with the authors:
