> 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/continuous-delivery/use-continuous-delivery/cd-building-blocks/advanced/cd-governance/opa-policies-for-cd-entities.md).

# OPA Policy for CD Entities

Use OPA policies with CD entities such as services, environments, infrastructure definitions, and overrides to enforce governance rules during save operations.

Open Policy Agent (OPA) is an open-source policy engine that enables you to write declarative policies and integrate them into decision-making processes.

Harness supports OPA policies for Continuous Delivery (CD) entities, including **Services**, **Environments**, **Infrastructure Definitions**, and **Overrides**. These policies enforce governance by evaluating predefined rules during entity operations such as creating or saving configurations.

***

## What you will learn from this topic

* **Policy creation:** How to define custom OPA policies for CD entities using the Harness UI.
* **OnSave enforcement:** How policies are evaluated during entity save operations to allow or deny actions.
* **Sample policies:** Common Rego patterns for services, environments, infrastructure definitions, and overrides.
* **Policy sets:** How to group and apply policies to specific entity types and trigger events.
* **GitX auto-creation control:** How OPA policies apply to entities created automatically via Git webhook events.

***

## Before you begin

Confirm the following before you create OPA policies for Continuous Delivery entities:

* **Harness account with CD enabled:** You need access to a Harness account with Continuous Delivery enabled.
* **OPA governance enabled:** Your account must have the governance feature enabled. Go to [Harness governance overview](https://developer.harness.io/docs/platform/governance/policy-as-code/harness-governance-overview) to review the platform-wide governance framework.
* **Policy permissions:** You need permissions to create and manage policies. Go to the [permissions reference](https://developer.harness.io/docs/platform/role-based-access-control/permissions-reference) to review required permissions.

***

## Create a policy

Follow these steps to create a policy through the Harness UI:

1. Go to **Settings** in Harness.
2. Under **Security and Governance**, click **Policies**.

![Policies section under Security and Governance in the Harness Settings menu](https://3694223630-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fy1JhZ4oKIppwY7d5AhPj%2Fuploads%2Fgit-blob-6c04be19102d8da07cdef1896764e4ab9601daa8%2Fopa-policy-1.png?alt=media)

3. In the **Policies** tab, click **+ New Policy**.
   * Enter a name for your policy.
   * Under **How do you want to set up your Policy**, select either **Inline** or **Remote**.
   * Click **Apply**.
4. Define the policy for your entity using the provided templates or write one manually.

![OPA policy editor showing the Rego editor with template options for CD entity types](https://3694223630-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fy1JhZ4oKIppwY7d5AhPj%2Fuploads%2Fgit-blob-15609bff65b0768c019b0c046b1f08a31030d73f%2Fopa-policy-2.png?alt=media)

5. Click **Save**.

### Sample policies

The following examples show policy patterns for each supported CD entity type. Select the sample that matches your entity type to expand it.

<details>

<summary>Service policy example</summary>

```rego
package abc

deny["denied"] {
  input.serviceEntity.serviceDefinition.type == "Kubernetes"
}

deny["denied"] {
  startswith(input.serviceEntity.name, "Kubernetes_service")
}
```

This policy denies the action if the service type is `Kubernetes`. It also denies the action if the service name starts with `Kubernetes_service`.

</details>

<details>

<summary>Environment policy example</summary>

```rego
package abc

deny {
  input.environmentEntity.type == "PreProduction"
}

deny {
  input.environmentEntity.variables[i].name == "variable"
}
```

This policy denies the action if the environment type is `PreProduction`. It also denies the action if there is a variable named `variable`.

</details>

<details>

<summary>Infrastructure definition policy example</summary>

```rego
package abc

deny["denied"]{
  input.infrastructureEntity.infrastructureDefinition.projectIdentifier == "k8s-Infrastructure"
  input.infrastructureEntity.infrastructureDefinition.deploymentType == "Kubernetes"
}
```

The policy denies the action if both of the following conditions are met:

* The `projectIdentifier` of the `infrastructureEntity` equals `k8s-Infrastructure`.
* The `deploymentType` of the `infrastructureEntity` is `Kubernetes`.

</details>

<details>

<summary>Overrides policy example</summary>

```rego
package abc

deny["String variable type not allowed"]{
  input.overrideEntity.overrides.variables[i].type == "String"
}

deny["Variables have to be required"]{
  input.overrideEntity.overrides.variables[i].required == false
}
```

The policy denies the action if either of the following conditions is met:

* A variable in the `overrideEntity.overrides.variables` array has its type set to `String`.
* A variable in the `overrideEntity.overrides.variables` array has its `required` field set to `false`.

</details>

***

## Configure a policy set

After you create your policies, apply them by configuring a policy set. A policy set groups one or more policies and defines which entity type and trigger event they apply to.

### Create a policy set

To create a policy set in the Harness UI, do the following:

1. In the **Policy Sets** tab, click **+ New Policy Set**.
2. On the **Overview** page:
   * Enter a **Name** for the policy set.
   * Under **Entity Type that this policy set applies to**, select the entity type. The supported entities are:
     * **Service**
     * **Environment**
     * **Infrastructure**
     * **Override**
   * Under **On what event should the policy set be evaluated**, select **On Save**.

![Policy set overview page showing entity type selection and On Save event trigger](https://3694223630-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fy1JhZ4oKIppwY7d5AhPj%2Fuploads%2Fgit-blob-3348562101d95321a2ff2831ec96ab3a46b94ba5%2Fopa-policy-3.png?alt=media)

3. On the **Policy Evaluation Criteria** page:
   * Click **+ Add Policy**.
   * Select the policy you created for the entity. You can also select policies created at the project, organization, and account levels.
   * Under **What should happen if a policy fails?**, select one of the following options:
     * **Warn & continue:** Displays a warning if the policy evaluation fails, but allows the entity to be saved.
     * **Error and exit:** Displays an error and prevents the entity from being saved.

![Policy evaluation criteria page showing policy selection and failure behavior options](https://3694223630-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fy1JhZ4oKIppwY7d5AhPj%2Fuploads%2Fgit-blob-1c1716aa396b148b1bc6e80d63b69c56f4132219%2Fopa-policy-4.png?alt=media)

The policy set is now enabled. The policy is enforced each time the entity is saved.

For example, if you have a policy that prevents the creation of a Kubernetes service, attempting to save a Kubernetes service returns the following error:

![Error message blocking the save of a Kubernetes service due to an OPA policy violation](https://3694223630-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fy1JhZ4oKIppwY7d5AhPj%2Fuploads%2Fgit-blob-f11601a923f85f2286bc72f7d54458e630a8a3da%2Fopa-policy-5.png?alt=media)

***

## Block GitX auto-creation with OPA policies

OPA **On Save** policies are also evaluated during **GitX auto-creation**, when entities are created automatically via webhook events after pushing YAML files to your Git repository. This lets you control which entities can be auto-created based on the type of principal and the repository.

When a webhook fires, Harness evaluates the applicable policy sets before creating each entity. If a policy denies the operation, the entity is not created and the webhook event is marked as a warning. Manual creation via the Harness UI or API is not affected because those actions carry `principalType == "USER"`, while webhook-triggered auto-creation uses `principalType == "SERVICE"`.

Go to [Control auto-creation with OPA policies](https://developer.harness.io/docs/platform/git-experience/autocreation-of-entities#control-auto-creation-with-opa-policies) to learn how to write policies for GitX auto-creation.

***

## Limitations

Be aware of the following limitations when using OPA policies with CD entities:

* **OnSave enforcement only:** Policies apply only during the **On Save** event. If an entity already exists, the policy is not enforced during deployment.
* **Dynamic branch evaluation:** Harness does not support evaluating environments using dynamically linked branches from the pipeline during OPA policy evaluation. The dynamic linked branch is determined by the parent entity (the pipeline), which is not accessible in the `EnvironmentExpansionHandler` context. This issue only occurs when the entity is created or moved to a branch other than `main` in the remote repository.

***

## Troubleshooting

<details>

<summary>Policy is not enforced during pipeline deployment</summary>

OPA policies for CD entities apply only during **On Save** events. If an entity was created before the policy was applied, or if the entity already exists, the policy is not evaluated at pipeline execution time. To enforce governance at pipeline runtime, go to [Harness governance overview](https://developer.harness.io/docs/platform/governance/policy-as-code/harness-governance-overview) to review pipeline-level policy options.

</details>

<details>

<summary>Environment policy does not evaluate with a dynamically linked branch</summary>

When an entity is created or moved to a branch other than `main` in a remote repository, OPA policy evaluation for dynamically linked branches is not supported. The dynamic linked branch is resolved from the parent pipeline entity, which is not accessible in the `EnvironmentExpansionHandler` context. To work around this, keep environment entities on the `main` branch when policy evaluation is required.

</details>

***

## Next steps

You have configured OPA policies and policy sets for your CD entities. You can extend governance further across your pipelines and the platform.

* [Harness governance overview](https://developer.harness.io/docs/platform/governance/policy-as-code/harness-governance-overview): Review the platform-wide policy-as-code framework and available entity types.
* [Sample policy use cases](https://developer.harness.io/docs/platform/governance/policy-as-code/sample-policy-use-case): Explore additional policy patterns across Harness modules.
* [GitX auto-creation of entities](https://developer.harness.io/docs/platform/git-experience/autocreation-of-entities): Understand how GitX creates entities from webhook events and how to control them with OPA policies.
