> For the complete documentation index, see [llms.txt](https://developer.harness.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developer.harness.io/harness-ai/use-harness-platform/governance/policy-as-code/policy-as-code-for-terraform.md).

# Policy as Code for Terraform

Learn how to create and enforce OPA policies on Terraform Plan, Terraform Plan Cost, and Terraform State.

Harness provides governance using Open Policy Agent (OPA), Policy Management, and Rego policies.

Harness supports three Terraform-related entity types for policy evaluation. Each entity type has its own set of evaluation events, letting you enforce governance at different stages of your Terraform workflow.

| Entity type             | Evaluation event                             | When it runs                                                        |
| ----------------------- | -------------------------------------------- | ------------------------------------------------------------------- |
| **Terraform Plan**      | After Terraform Plan                         | After a Terraform Plan step completes in a pipeline                 |
| **Terraform Plan Cost** | After Terraform Plan                         | After a Terraform Plan step completes (evaluates the cost estimate) |
| **Terraform State**     | After Terraform Plan / After Terraform Apply | After a Terraform Plan or Terraform Apply step completes            |

Go to [Harness Governance Quickstart](/harness-ai/use-harness-platform/governance/policy-as-code/harness-governance-quickstart.md) to set up governance before you create these policies.

### Prerequisites <a href="#prerequisites" id="prerequisites"></a>

Complete these steps before you create a policy for Terraform entities.

* [Harness Governance Overview](/harness-ai/use-harness-platform/governance/policy-as-code/harness-governance-overview.md)
* [Harness Governance Quickstart](/harness-ai/use-harness-platform/governance/policy-as-code/harness-governance-quickstart.md)
* Policies use the OPA authoring language Rego. Go to [OPA Policy Authoring](https://academy.styra.com/courses/opa-rego) to learn Rego syntax.

### Sample policies in the library <a href="#sample-policies-in-the-library" id="sample-policies-in-the-library"></a>

Harness ships four built-in sample policies for Terraform entities. You can find them in the **Library** panel by searching for "terraform":

![Terraform sample policies in the Library panel](https://173309742-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3F2TpHXhur2QtQnORSM9%2Fuploads%2Fgit-blob-2781b954bb38f7831ee1e47d47555d9e23676533%2Fterraform-sample-policies.png?alt=media)

| Sample policy                                     | Entity type         | Description                                                                     |
| ------------------------------------------------- | ------------------- | ------------------------------------------------------------------------------- |
| **Terraform Plan – EC2**                          | Terraform Plan      | Ensures the Terraform plan meets required EC2 criteria                          |
| **Terraform State – EC2**                         | Terraform State     | Ensures the Terraform state meets required EC2 criteria                         |
| **Terraform Plan Cost – Cost Estimate Increased** | Terraform Plan Cost | Ensures cost estimate has not increased more than 10% compared to the last plan |
| **Terraform Plan Cost – Total Cost Estimate**     | Terraform Plan Cost | Ensures the total cost does not exceed a specified amount                       |

### Terraform plan <a href="#terraform-plan" id="terraform-plan"></a>

#### Overview <a href="#overview" id="overview"></a>

A Terraform Plan policy evaluates the planned infrastructure changes before they are applied. Use this to enforce rules on what resources can be created, modified, or destroyed.

The policy is evaluated on the event:

* **After Terraform Plan**: evaluated after a Terraform Plan step completes in a pipeline.

![Terraform Plan policy set, entity type and event](https://173309742-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3F2TpHXhur2QtQnORSM9%2Fuploads%2Fgit-blob-4df26a4f5435abf5fe5bc50a18c667112cde43ac%2Fterraform-plan-event.png?alt=media)

#### Step 1: Add a policy <a href="#step-1-add-a-policy" id="step-1-add-a-policy"></a>

Create the Rego policy that evaluates Terraform Plan data.

1. In Harness, go to **Account Settings** → **Policies** → **New Policy**.
2. Enter a **Name** for your policy and click **Apply**.
3. Add your Rego policy in the editor. You can use a sample from the **Library** (search "Terraform Plan") or write your own.

   Below is an example that blocks plans creating EC2 instances of a disallowed type:

```rego
package terraform_plan

deny[msg] {
  resource := input.plan.resource_changes[_]
  resource.type == "aws_instance"
  resource.change.after.instance_type == "t2.micro"
  msg := sprintf("Resource '%s' uses instance type 't2.micro' which is not allowed. Use 't3.micro' or larger.", [resource.address])
}
```

4. Click **Save**.

#### Step 2: Add the policy to a policy set <a href="#step-2-add-the-policy-to-a-policy-set" id="step-2-add-the-policy-to-a-policy-set"></a>

Add the policy to a policy set scoped to the Terraform Plan entity type.

1. Go to **Policies** → **Policy Sets** → **New Policy Set**.
2. Enter a **Name** and optional **Description**.
3. In **Entity type**, select **Terraform Plan**.
4. In **On what event should the Policy Set be evaluated**, select **After Terraform Plan**.
5. Click **Continue**.
6. In **Policy evaluation criteria**, click **Add Policy** and select your policy.
7. Select the severity:
   * **Warn & continue**: a warning is displayed but the pipeline continues.
   * **Error and exit**: the pipeline fails if the policy is not met.
8. Click **Apply**, then click **Finish**.

### Terraform plan cost <a href="#terraform-plan-cost" id="terraform-plan-cost"></a>

#### Overview <a href="#overview" id="overview"></a>

A Terraform Plan Cost policy evaluates the estimated cost of planned infrastructure changes. Use this to set cost guardrails and prevent unexpected spending.

The policy is evaluated on the event:

* **After Terraform Plan**: evaluated after a Terraform Plan step completes, using the cost estimate data.

![Terraform Plan Cost policy set, entity type and event](https://173309742-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3F2TpHXhur2QtQnORSM9%2Fuploads%2Fgit-blob-364fe7af356ee012c15628fd4cd9f4fab39a0889%2Fterraform-plan-cost-event.png?alt=media)

#### Step 1: Add a policy <a href="#step-1-add-a-policy" id="step-1-add-a-policy"></a>

Create the Rego policy that evaluates the Terraform Plan Cost estimate.

1. In Harness, go to **Account Settings** → **Policies** → **New Policy**.
2. Enter a **Name** for your policy and click **Apply**.
3. Add your Rego policy in the editor. Below are two examples matching the built-in samples.

**Block cost increases over 10%**

```rego
package terraform_plan_cost

deny[msg] {
  currentCost := input.costs.totalMonthlyCost
  previousCost := input.costs.pastTotalMonthlyCost
  previousCost > 0
  increase := ((currentCost - previousCost) / previousCost) * 100
  increase > 10
  msg := sprintf("Terraform plan cost increased by %.1f%%, which exceeds the 10%% threshold. Previous: $%.2f, Current: $%.2f", [increase, previousCost, currentCost])
}
```

**Block plans exceeding a total cost limit**

```rego
package terraform_plan_cost

deny[msg] {
  totalCost := input.costs.totalMonthlyCost
  totalCost > 1000
  msg := sprintf("Terraform plan total monthly cost estimate is $%.2f, which exceeds the $1000 limit.", [totalCost])
}
```

4. Click **Save**.

#### Step 2: Add the policy to a policy set <a href="#step-2-add-the-policy-to-a-policy-set" id="step-2-add-the-policy-to-a-policy-set"></a>

Add the policy to a policy set scoped to the Terraform Plan Cost entity type.

1. Go to **Policies** → **Policy Sets** → **New Policy Set**.
2. Enter a **Name** and optional **Description**.
3. In **Entity type**, select **Terraform Plan Cost**.
4. In **On what event should the Policy Set be evaluated**, select **After Terraform Plan**.
5. Click **Continue**.
6. In **Policy evaluation criteria**, click **Add Policy** and select your policy.
7. Select the severity (**Warn & continue** or **Error and exit**).
8. Click **Apply**, then click **Finish**.

### Terraform state <a href="#terraform-state" id="terraform-state"></a>

#### Overview <a href="#overview" id="overview"></a>

A Terraform State policy evaluates the current state of your Terraform-managed infrastructure. Use this to audit existing resources and ensure ongoing compliance.

The policy is evaluated on the events:

* **After Terraform Plan**: evaluated after a Terraform Plan step completes.
* **After Terraform Apply**: evaluated after a Terraform Apply step completes.

![Terraform State policy set, entity type and events](https://173309742-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3F2TpHXhur2QtQnORSM9%2Fuploads%2Fgit-blob-80af0e0cac8352f25db00b6d17e56408b68a9835%2Fterraform-state-event.png?alt=media)

#### Step 1: Add a policy <a href="#step-1-add-a-policy" id="step-1-add-a-policy"></a>

Create the Rego policy that evaluates Terraform State data.

1. In Harness, go to **Account Settings** → **Policies** → **New Policy**.
2. Enter a **Name** for your policy and click **Apply**.
3. Add your Rego policy in the editor. Below is an example that checks EC2 instance types in the current state:

```rego
package terraform_state

deny[msg] {
  resource := input.state.resources[_]
  resource.type == "aws_instance"
  instance := resource.instances[_]
  instance.attributes.instance_type == "t2.micro"
  msg := sprintf("Resource '%s' uses instance type 't2.micro' in the current state. Migrate to 't3.micro' or larger.", [resource.name])
}
```

4. Click **Save**.

#### Step 2: Add the policy to a policy set <a href="#step-2-add-the-policy-to-a-policy-set" id="step-2-add-the-policy-to-a-policy-set"></a>

Add the policy to a policy set scoped to the Terraform State entity type.

1. Go to **Policies** → **Policy Sets** → **New Policy Set**.
2. Enter a **Name** and optional **Description**.
3. In **Entity type**, select **Terraform State**.
4. In **On what event should the Policy Set be evaluated**, select **After Terraform Plan** or **After Terraform Apply**.
5. Click **Continue**.
6. In **Policy evaluation criteria**, click **Add Policy** and select your policy.
7. Select the severity (**Warn & continue** or **Error and exit**).
8. Click **Apply**, then click **Finish**.

### Policy set entity type selection <a href="#policy-set-entity-type-selection" id="policy-set-entity-type-selection"></a>

When creating a policy set, the **Entity Type** dropdown lists all three Terraform entity types separately:

![Entity type dropdown showing Terraform options](https://173309742-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3F2TpHXhur2QtQnORSM9%2Fuploads%2Fgit-blob-f4d2caa0495a51b4810cd4fb1a00e1f162b32e58%2Fterraform-plan-entity-type.png?alt=media)

Each entity type must have its own policy set: you cannot mix Terraform Plan, Terraform Plan Cost, and Terraform State policies in a single policy set.

### See also <a href="#see-also" id="see-also"></a>

Related governance topics cover the broader policy set workflow.

* [Harness Governance Overview](/harness-ai/use-harness-platform/governance/policy-as-code/harness-governance-overview.md)
* [Policy Samples](/harness-ai/use-harness-platform/governance/policy-as-code/sample-policy-use-case.md)

### Next steps <a href="#next-steps" id="next-steps"></a>

Continue your governance setup with these related resources.

* Go to [Policy Samples](/harness-ai/use-harness-platform/governance/policy-as-code/sample-policy-use-case.md) to see more Rego examples for Terraform Plan, Terraform Plan Cost, and Terraform State policies.
* Go to [Harness Governance Overview](/harness-ai/use-harness-platform/governance/policy-as-code/harness-governance-overview.md) to understand how policy sets fit into the wider governance model.
* Go to [Harness Governance Quickstart](/harness-ai/use-harness-platform/governance/policy-as-code/harness-governance-quickstart.md) to review the overall governance setup steps.

{% @harness-feedback/feedback module="harness-ai" pagePath="harness-ai/use-harness-platform/governance/policy-as-code/policy-as-code-for-terraform" %}
