Home United States USA — software What Is Open Policy Agent and How It Works

What Is Open Policy Agent and How It Works

151
0
SHARE

What is Open Policy Agent (OPA)? See Open Policy Agent examples and a full tutorial on when to use it.
Join the DZone community and get the full member experience. Open Policy Agent is an open-source engine that provides a way of declaratively writing policies as code and then using those policies as part of a decision-making process. It uses a policy language called Rego, allowing you to write policies for different services using the same language. OPA can be used for a number of purposes, including: OPA was originally created by Styra, and is now part of the Cloud Native Computing Foundation (CNCF), alongside other CNCF technologies like Kubernetes and Prometheus. In this article, I will give an overview of Open Policy Agent, explain why you would want to use it, as well as showcase how you can use OPA with your Spacelift account. Although OPA can serve many purposes, I’m going to focus on how it can be used alongside Infrastructure as Code. We can visualise how OPA works using the following diagram: As you can see, OPA accepts a policy, input and query, and based on that, generates a response. The input can be any valid JSON document, allowing OPA to integrate with any tool that produces JSON output. In the following sections, I’ll go into more specific examples of using OPA that should help make things clearer but before I do, here’s a quick list of reasons why I’m interested in using OPA: Let’s try to make that a bit less theoretical by using a specific example: Terraform. Terraform can produce a plan in JSON format via the terraform show command. This means that we can define policies for our infrastructure, and use OPA to make a decision about whether a plan is safe to apply or not: For example, say we have the following Terraform definition to create an EC2 instance: Now, say we want to ensure that every Terraform resource has a Name tag. We could enforce that by creating a file called plan.rego with the following content: In order to use OPA to evaluate our policy, we need to take the following steps: To get a JSON representation of our plan, we need to output our plan to a file, and then use the terraform show command to output that plan as JSON: We can then use opa eval to evaluate our plan against our policy: As you can see, we’re using the query data.spacelift.allow because our policy is loaded as a data file, and we defined our allow rule in the spacelift namespace. You can also see that opa eval produced an empty output ({}). This means that our allow rule didn’t evaluate to true, and so produced no output. Let’s adjust our Terraform definition to include a Name tag: Now if we generate our plan and evaluate the policy again, we should get a slightly different output: This tells us that the allow rule has evaluated true.

Continue reading...