This is part one of a four blog series on OPA usage with Terraform. This first blog will cover the basics of how to use OPA to evaluate and enforce policy on your Terraform plans. The next three blogs will cover more details around how to evaluate the plan JSON and write the actual OPA policies.
Create the Terraform Plan & OPA Policy
The general flow to create an OPA policy and check the Terraform plan is as follows:
Create Terraform Plan -> Convert to JSON -> Run OPA Check
1. Create the Terraform Plan
The Terraform plan step works just like any other plan, but you need to ensure that you save the output so that it can be converted into JSON at a later stage.
terraform plan --out=FILENAME
2. Convert the plan into JSON
Next, you want to convert the plan to JSON so that it can be read by OPA.
terraform show -json FILENAME > FILENAME.json
The result being:
3. Create the OPA code
Now that you have the plan converted to JSON, you can write OPA code to check the plan before you run an apply. Given that OPA is policy as code, you can write any policy you want as long as the values you are referring to exist in the Terraform plan JSON file.
In this example, we will start simple by checking to ensure that only approved AWS resources are being created. The example Terraform plan shows that an AWS instance will be created, which is not an approved resource as seen in the OPA policy below. The first step in writing an OPA policy for Terraform is to declare that the package is Terraform. Next, you need to import the tfplan. Last, write the logic to check the JSON.
OPA policy files require the .rego extension, e.g. my_policy.rego
4. Check the Terraform plan against the OPA policy
To check the plan, run the following command:
opa eval --format pretty --data FILENAME.rego --input FILENAME.json "data.terraform"
The result being that OPA identified that the Terraform plan will violate the policy based on the creation of an AWS instance resource.
That’s all there is to it! The actual OPA code can get much more complex based on your use and you can manipulate the plan based on the tooling you are using, but these are the basics to creating OPA checks against your Terraform plan.
In the next article in the series, we take a detailed look at writing OPA policies for Terraform and Scalr, including explanations of the more commonly used OPA language elements.
OPA Series Part 2: OPA Logic and Structure for Scalr