> 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/feature-management-experimentation/management-and-administration/policies.md).

# Policies

Learn how to create and enforce Harness Policy As Code (OPA) policies for Feature Management & Experimentation (FME) entities.

Harness Policy As Code lets Feature Management & Experimentation (FME) administrators define governance rules that are automatically evaluated whenever supported FME entities are created, updated, deleted, or archived.

Policies can govern feature flag targeting logic, rollout configurations, flag lifecycles, FME environments, and segments. They apply to changes made by users in Harness, as well as changes triggered by automations and Harness pipeline steps.

Policies are authored in [Rego](https://www.openpolicyagent.org/docs/latest/policy-language/) and evaluated using [Open Policy Agent (OPA)](https://www.openpolicyagent.org/).

Harness provides out-of-the-box policies for FME that cover common governance requirements across feature flags, environments, and segments.

| FME entity               | Out-of-the-box policies                                   |
| ------------------------ | --------------------------------------------------------- |
| Feature Flags            | Naming Convention, Required Tags, Team Ownership Required |
| Feature Flag Definitions | Validation Rules                                          |
| Environments             | Naming Convention, Production Requires Approvals          |
| Segments                 | Naming Convention                                         |
| Segment Definitions      | Validation Rules, Exclude High Priority Users             |

All policies are [evaluated](#how-policies-are-evaluated) on **On Save** events across these entities.

***

## Before you begin

Before you create a policy, confirm the following:

* **Policy As Code knowledge:** Understand policies, policy sets, and enforcement. Go to the [Harness Policy As Code overview](https://developer.harness.io/harness-platform/use-harness-platform/governance/policy-as-code/harness-governance-overview) to review these concepts.
* **Permissions:** You need the **Governance Policies** and **Governance Policy Sets** permissions to create and enforce policies. Go to the [permissions reference](https://developer.harness.io/harness-platform/use-harness-platform/platform-access-control/permissions-reference#policies) to assign them through a custom role. In migrated FME environments, administrators may have these permissions through the **Account Admin** role.
* **Rego:** Policies are written in Rego. If you are new to Rego, go to the [Open Policy Agent documentation](https://www.openpolicyagent.org/docs) to learn the language.

***

## Access Harness policies <a href="#access-harness-policies" id="access-harness-policies"></a>

When you navigate to the **Policies** page from **Project**, **Account**, or **Organization Settings**, you can manage policies, policy sets, and evaluations across the following tabs.

{% tabs %}
{% tab title="Overview" %}
The **Overview** tab displays a high-level view of policy health across your project, account, or organization. This includes charts for policy evaluations, summary counts for policy sets and total evaluations, and the total number of policies.

![Policy health overview dashboard](https://1473625385-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrT2RGHAjtBTaObzchfpb%2Fuploads%2Fgit-blob-d0a2a530087d2dec878d6becb8ffdf345fe62b12%2Fpolicies-1.png?alt=media)

Select the dropdown menu to view the policy health in the `Last 24 hours`, `Last 7 days`, and `Last 30 days`. Use this view to understand how policies are performing and whether violations are increasing or decreasing.
{% endtab %}

{% tab title="Policies" %}
The **Policies** tab displays a list view of individual policies. To create a policy, select **+ New Policy**.

![Policies list view](https://1473625385-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrT2RGHAjtBTaObzchfpb%2Fuploads%2Fgit-blob-5752da273dca2ecdf8823924d15d1d0950c19a82%2Fpolicies-2.png?alt=media)

Each row represents a single policy and includes the following information:

| Column                     | Description                            |
| -------------------------- | -------------------------------------- |
| **Policy**                 | Name of the policy                     |
| **Policy Store**           | Inline or Remote (Git-backed)          |
| **Referenced Policy Sets** | Number of policy sets using the policy |
| **Created At**             | Policy creation timestamp              |
| **Last Modified**          | Most recent update                     |

Use the search bar to search for policies by name, and the dropdown menu to sort policies using filters such as `Last Updated`, `A-Z, 0-9`, or `Z-A, 9-0`. To manage your policies, select the **More** icon (⋮) on a policy and select **Edit** or **Delete**.
{% endtab %}

{% tab title="Policy Sets" %}
The **Policy Sets** tab shows a list view of policy sets, which group one or more policies and define enforcement behavior. To create a policy set, select **+ New Policy Set**.

![Policy sets list view](https://1473625385-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrT2RGHAjtBTaObzchfpb%2Fuploads%2Fgit-blob-6a98218635b0f6618f289b4d7f68973c6b56b6e3%2Fpolicies-3.png?alt=media)

Each row represents a single policy set and includes the following information:

| Column            | Description                                                                                                 |
| ----------------- | ----------------------------------------------------------------------------------------------------------- |
| **Policy Set**    | Name of the policy set                                                                                      |
| **Environment**   | Environment where the policy set applies (for FME, this is `Harness`)                                       |
| **Action**        | Trigger event (for FME, this is **On Save**)                                                                |
| **Enforced**      | Whether enforcement is enabled                                                                              |
| **Entity Type**   | Type of entity (`Feature Flag`, `Feature Flag Definition`, `Environment`, `Segment`, `Segment Definition` ) |
| **Created At**    | Creation timestamp                                                                                          |
| **Last Modified** | Most recent update                                                                                          |

Use the search bar to search for policy sets by name, and the dropdown menu to sort policy sets using filters such as `Last Updated`, `A-Z, 0-9`, or `Z-A, 9-0`. To manage your policy sets, select the **More** icon (⋮) on a policy set and select **Edit** or **Delete**.
{% endtab %}

{% tab title="Evaluations" %}
The **Evaluations** tab provides a list view of individual policy evaluations, allowing you to audit policy enforcement results.

![Evaluations list view](https://1473625385-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrT2RGHAjtBTaObzchfpb%2Fuploads%2Fgit-blob-26140a5930ee7d8736e9664a83a830602e201244%2Fpolicies-4.png?alt=media)

You can filter evaluations using the time range dropdown menu (for example, `Last 7 days`). Each evaluation includes the following information:

| Column           | Description                                                                                                 |
| ---------------- | ----------------------------------------------------------------------------------------------------------- |
| **Entity**       | Name of the evaluated entity                                                                                |
| **Entity Type**  | Type of entity (`Feature Flag`, `Feature Flag Definition`, `Environment`, `Segment`, `Segment Definition` ) |
| **Execution**    | Internal execution identifier                                                                               |
| **Evaluated On** | When the evaluation occurred                                                                                |
| **Action**       | Trigger event (for FME, this is **On Save**)                                                                |
| **Status**       | Evaluation result: **Success**, **Failed**, or **Warning**                                                  |

This view is useful for troubleshooting failed saves and validating that policies are being enforced as expected.
{% endtab %}
{% endtabs %}

***

## Create and enforce a policy <a href="#create-and-enforce-a-policy" id="create-and-enforce-a-policy"></a>

To create a policy:

1. From the Harness FME navigation menu, select **Project**, **Account**, or **Organization Settings**.
2. Under **Security and Governance**, select **Policies**. The **Overview** tab opens and displays overall policy health over a selected time range.
3. Select the **Policies** tab, then select **+ New Policy**. Optionally, you can [import a policy from Git](https://developer.harness.io/harness-platform/use-harness-platform/governance/policy-as-code/configure-gitexperience-for-opa) by opening the dropdown menu and selecting **Import from Git**.
4. Enter a name for the policy and select the setup option:
   * **Inline** to author the policy in the Harness editor.
   * **Remote** to reference a Rego policy stored in a Git repository. Select a connector, repository, branch, and Rego path, then select **Apply**.
5. This opens the Policy Editor view, where you can author your own policy or use an out-of-the-box sample.

   ![Policy editor view](https://1473625385-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrT2RGHAjtBTaObzchfpb%2Fuploads%2Fgit-blob-59a93e4473488f21d0f4fdf756374f8be315bff6%2Fpolicies-6.png?alt=media)

   The editor includes a code editor for writing or modifying Rego, a **Testing Terminal** tab to validate policy behavior, and a **Library** tab containing sample policies.

   ![FME policy library tab with sample policies](https://1473625385-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrT2RGHAjtBTaObzchfpb%2Fuploads%2Fgit-blob-765a72f4d317eb73ed14649758b5d5c6c3b8b636%2Fpolicies-15.png?alt=media)
6. Test the policy by opening the **Testing Terminal** tab.
7. Select **Select Input**.
8. Choose the appropriate inputs, including the entity type, organization, project, and action (**On Save**). Then, select an entity from the list of results.

   ![Select input for policy testing](https://1473625385-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrT2RGHAjtBTaObzchfpb%2Fuploads%2Fgit-blob-4d18bc04a6e37f3fd3ce8e7817168e2492980c48%2Fpolicies-7.png?alt=media)
9. Select **Apply**, then select **Test**. Review the output to confirm the policy behaves as expected.
10. Select **Next: Enforce Policy**.
11. Configure the following enforcement settings:
    * **Scope**: Select the appropriate scope, for example: `Account`.
    * **Trigger event**: Select **On Save**.
    * **Severity**:
      * **Warn and Continue**: Violations generate a warning, but the entity is saved.
      * **Error and Exit**: Violations block the save operation.
12. Select **You're all set!** to save and enforce the policy.

{% hint style="info" %}
**Policies do not apply retroactively**

Existing FME entities are not automatically evaluated against new policies. A policy runs only when a supported FME entity (a feature flag, feature flag definition, environment, segment, or segment definition) is created, updated, deleted, or archived. To evaluate an existing entity, save it again.
{% endhint %}

***

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

After you create an individual policy, add it to a policy set before it is enforced on FME entities. Policy sets group policies and configure where they are enforced.

To add a policy set:

1. Select the **Policy Sets** tab.
2. Select **+ New Policy Set**.
3. In the **Overview** section, enter a name and optionally, include a description.
4. Select the entity type that this policy set applies to: **FME Feature Flag**, **FME Feature Flag Definition**, **FME Environment**, **FME Segment**, or **FME Segment Definition**.
5. Select **On Save** as the trigger event.
6. Select **Continue**.

   ![New policy set configuration](https://1473625385-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrT2RGHAjtBTaObzchfpb%2Fuploads%2Fgit-blob-b2b04023294a2030be78c9be37d578d58e9876fc%2Fpolicies-8.png?alt=media)
7. In the **Policy evaluation criteria** section, select **+ Add Policy**.
8. Select a policy written for the entity type you chose in step 4.

   ![Add policy to a policy set](https://1473625385-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrT2RGHAjtBTaObzchfpb%2Fuploads%2Fgit-blob-08bd0e0d19e682b3a792ab28c221ac85d1b25bbd%2Fpolicies-9.png?alt=media)
9. To the right of the policy, select **Warn and Continue** or **Error and Exit**.
   * **Warn and Continue**: If a policy is not met when an entity is evaluated, you receive a warning but the entity is saved.
   * **Error and Exit**: If a policy is not met when an entity is evaluated, you receive an error and the entity is not saved.
10. Select **Apply**.
11. To add an additional policy, select **+ Add Policy**. When you finish adding policies to a policy set, select **Finish**.

    ![Policy set with policies added](https://1473625385-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrT2RGHAjtBTaObzchfpb%2Fuploads%2Fgit-blob-38a148ffddc9cc90619b9f3301ef02909713ba70%2Fpolicies-10.png?alt=media)
12. In the **Policy Sets** list, select the **Enforced** checkbox for the policy set you created.

    ![Enforced checkbox for policy set](https://1473625385-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrT2RGHAjtBTaObzchfpb%2Fuploads%2Fgit-blob-a3876da2564d5f095bb58af30c733da4a076eec4%2Fpolicies-11.png?alt=media)

***

## How policies are evaluated <a href="#how-policies-are-evaluated" id="how-policies-are-evaluated"></a>

Policies are evaluated whenever an entity is created, updated, deleted, or archived. The input payload sent to OPA includes an `entityMetadata.changeTrigger` field (`create`, `update`, `delete`, or `archive`) so you can write policies that apply to specific change types.

{% tabs %}
{% tab title="Feature Flag" %}
An **FME Feature Flag** policy is evaluated when you change a feature flag's metadata. Examples of changes that trigger evaluation:

* Creating a new feature flag
* Updating a flag's name, description, tags, or metrics
* Archiving or deleting a feature flag
  {% endtab %}

{% tab title="Feature Flag Definition" %}
An **FME Feature Flag Definition** policy is evaluated when you change a feature flag's targeting configuration in a specific environment. Examples of changes that trigger evaluation:

* Adding or modifying targeting rules
* Changing rollout percentages or traffic allocation
* Updating the default treatment
* Killing or restoring a flag in an environment
  {% endtab %}

{% tab title="Environment" %}
An **FME Environment** policy is evaluated when you create or modify environments in **FME Settings**. Examples of changes that trigger evaluation:

* Creating a new environment
* Updating the environment type
* Modifying approval requirements or approvers
* Updating data export permission settings
  {% endtab %}

{% tab title="Segment" %}
A **Segment** policy is evaluated when you create or update a segment. Examples of changes that trigger evaluation:

* Creating a new segment
* Updating the segment name
* Modifying segment descriptions, tags, or owners
  {% endtab %}

{% tab title="Segment Definition" %}
A **Segment Definition** policy is evaluated when you change a segment's definition or targeting logic. Examples of changes that trigger evaluation:

* Adding or removing users in a segment
* Defining or modifying rule-based conditions
  {% endtab %}
  {% endtabs %}

On success, the change is applied. On failure, the result depends on the severity you configured:

* **Warn and Continue**: The change is applied, but you receive a warning message.
* **Error and Exit**: The change is blocked, and you receive an error message.

Changes made by [FME pipeline steps](/feature-management-experimentation/management-and-administration/pipelines.md) and automations are evaluated the same way. When **Error and Exit** blocks a change made by a pipeline step, the step fails and the pipeline follows its [failure strategy](https://developer.harness.io/harness-platform/use-harness-platform/pipelines/failure-handling/define-a-failure-strategy-on-stages-and-steps).

{% hint style="info" %}
**Use `changeTrigger` to scope your policies**

The `entityMetadata.changeTrigger` field in the input payload lets you target specific operations. For example, you might skip name convention checks on `delete` to avoid blocking cleanup of legacy flags. Go to the **Feature Flag** example in the [input payload reference](#input-payload-reference) for a policy that excludes delete operations.
{% endhint %}

***

## Manage policy evaluations <a href="#manage-policy-evaluations" id="manage-policy-evaluations"></a>

Select the **Evaluations** tab to view all successful, warning, and failed policy set evaluations. Use the **Type** dropdown menu to filter by entities, and the **Action** dropdown menu to filter by **On Save** events.

![Evaluations filtered by entity type](https://1473625385-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrT2RGHAjtBTaObzchfpb%2Fuploads%2Fgit-blob-20cc9cd158e50aeb3fd3f2aaa9f03e63e8e11660%2Fpolicies-5.png?alt=media)

Use the **Status** dropdown menu to filter evaluations by **Success**, **Failed**, or **Warning**. You can also use the time range selector to switch to a custom time range or a preset such as the past week, past month, or past three months.

![Evaluations filtered by status](https://1473625385-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrT2RGHAjtBTaObzchfpb%2Fuploads%2Fgit-blob-ef68addb84d1b4639c74c82a76ee4014a224a74b%2Fpolicies-12.png?alt=media)

Select an evaluation in the list to access the policy set that was evaluated. You can then open the policy set details to see associated policies, or open the policy definition itself.

{% tabs %}
{% tab title="Policy Set" %}
![Policy set evaluation details](https://1473625385-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrT2RGHAjtBTaObzchfpb%2Fuploads%2Fgit-blob-67e81bab50a5572f650786ca0a47285578817e42%2Fpolicies-13.png?alt=media)

From here, you can review which policies were applied and their evaluation results.
{% endtab %}

{% tab title="Policy" %}
![Policy definition details](https://1473625385-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrT2RGHAjtBTaObzchfpb%2Fuploads%2Fgit-blob-59a93e4473488f21d0f4fdf756374f8be315bff6%2Fpolicies-6.png?alt=media)

From here, you can review the Rego logic that was evaluated and update it if needed.
{% endtab %}
{% endtabs %}

***

## Input payload reference <a href="#input-payload-reference" id="input-payload-reference"></a>

When a policy is evaluated, Harness sends an input payload to OPA containing the entity data and metadata. The payload structure depends on the entity type.

{% hint style="info" %}
**Policies and policy sets apply to a single entity type**

**Each policy** must apply to exactly **one entity type**. For example, you can create a policy for Segment naming conventions, and another policy for adding IDs to Segment Definitions. Do not combine both of these validations into one policy.

**Each policy set** must also apply to exactly **one entity type** (and one event). For the FME entity types the event is **On Save**. The entity type you choose for the *policy set* determines the **payload** passed to each *policy* in the set. Therefore, for example, a policy for Segments and another policy for Segment Definitions must be added to different policy sets.

Harness activates an event listener for every enforced policy set. When the *event* on the *entity type* triggers the policy set to evaluate, an identical payload is passed to each policy in the set.
{% endhint %}

In Rego, access payload fields through `input`, for example `input.featureFlag.name` or `input.entityMetadata.changeTrigger`. Payloads that correspond to each FME entity type are shown below, along with Rego policy examples.

<details>

<summary>Feature Flag</summary>

```json
{
  "featureFlag": {
    "name": "ff_enable_dark_mode",
    "description": "Enables UI dark mode",
    "hasPendingStatusChange": false,
    "pendingChangeRequests": 0,
    "status": "active",
    "tags": ["ui", "frontend"],
    "trafficType": {
      "id": "c8bcb9e0-dc3e-...",
      "name": "user"
    }
  },
  "context": {
    "featureFlagDefinitions": []
  },
  "entityMetadata": {
    "actor": {
      "id": "2PeIU7FK...",
      "type": "user"
    },
    "changeTrigger": "create",
    "owners": [
      {
        "id": "2PeIU7FK...",
        "ownerId": "2PeIU7FK...",
        "ownerType": "user"
      }
    ],
    "project": {
      "id": "mobile_shopping_app"
    },
    "trafficType": {
      "id": "c8bcb9e0-dc3e-...",
      "name": "user"
    }
  }
}
```

The following policy denies creating or updating a feature flag if the description is missing or empty. It uses `changeTrigger` to skip validation on delete, so that flags with missing descriptions can still be cleaned up.

```rego
package fme_feature_flags

deny[msg] {
  input.entityMetadata.changeTrigger != "delete"
  not input.featureFlag.description
  msg := sprintf(
    "Feature flag '%s' must include a description before it can be saved",
    [input.featureFlag.name]
  )
}

deny[msg] {
  input.entityMetadata.changeTrigger != "delete"
  input.featureFlag.description == ""
  msg := sprintf(
    "Feature flag '%s' must include a non-empty description",
    [input.featureFlag.name]
  )
}
```

Go to [FME feature flag policies](https://developer.harness.io/harness-platform/use-harness-platform/governance/policy-as-code/sample-policy-use-case#fme-feature-flag-policies) to view more examples.

</details>

<details>

<summary>Feature Flag Definition</summary>

```json
{
  "featureFlagDefinition": {
    "id": "c8468cc-11f0-...",
    "name": "ff_enable_dark_mode",
    "description": "Enables UI dark mode",
    "defaultAllocation": {
      "size": 100,
      "treatment": "off"
    },
    "definition": [
      {
        "conditionType": "ROLLOUT",
        "label": "Default treatment",
        "matcherGroup": {
          "combiner": "AND",
          "matchers": [
            {
              "matcherType": "ALL_KEYS",
              "negate": false
            }
          ]
        },
        "partitions": [
          {
            "size": 100,
            "treatment": "off"
          }
        ]
      }
    ],
    "dependents": [],
    "environment": {
      "name": "Production",
      "type": "production"
    },
    "flagSets": [],
    "killed": false,
    "status": "active",
    "trafficAllocation": 100,
    "trafficType": {
      "id": "c8bcb9e0-dc3e-...",
      "name": "user"
    },
    "treatments": [
      {
        "name": "on",
        "description": "Enable dark mode",
        "baseline": false
      },
      {
        "name": "off",
        "description": "Keep dark mode disabled",
        "baseline": true,
        "defaultTreatment": true
      }
    ]
  },
  "context": {
    "featureFlag": {
      "id": "b47771f0...",
      "name": "ff_enable_dark_mode",
      "status": "active",
      "trafficType": {
        "id": "c8bcb9e0-dc3e-...",
        "name": "user"
      }
    },
    "featureFlagDefinitions": [],
    "pipelineExecution": {
      "pipelineIdentifier": "fme_change_pipeline",
      "executionId": "exec_01HXYZABCDEFGHJKLMNPQRST"
    }
  },
  "entityMetadata": {
    "actor": {
      "id": "2PeIU7FK...",
      "type": "user"
    },
    "changeTrigger": "update",
    "owners": [
      {
        "id": "2PeIU7FK...",
        "ownerId": "2PeIU7FK...",
        "ownerName": "miaknowles",
        "type": "user"
      }
    ],
    "project": {
      "id": "mobile_shopping_app"
    },
    "trafficType": {
      "id": "c8bcb9e0-dc3e-...",
      "name": "user"
    }
  }
}
```

The following policy ensures that every feature flag definition saved in a production environment belongs to at least one flag set.

```rego
package fme_feature_flag_definitions

deny[msg] {
  lower(input.featureFlagDefinition.environment.type) == "production"
  count(input.featureFlagDefinition.flagSets) == 0
  msg := sprintf(
    "Feature flag '%s' in Production must belong to at least one flag set",
    [input.featureFlagDefinition.name]
  )
}
```

Go to [FME feature flag definition policies](https://developer.harness.io/harness-platform/use-harness-platform/governance/policy-as-code/sample-policy-use-case#fme-feature-flag-definition-policies) to view more examples.

</details>

<details>

<summary>Environment</summary>

```json
{
  "fmeEnvironment": {
    "name": "Development",
    "environmentType": "pre_production",
    "changeSettings": {
      "approvalsSkippableBy": [],
      "approvers": [],
      "areApprovalsRequired": false,
      "areApproversRestricted": false,
      "areKillsAllowedWithoutApproval": false
    },
    "status": "active"
  },
  "entityMetadata": {
    "actor": {
      "id": "2PeIU7FK...",
      "type": "user"
    },
    "changeTrigger": "create",
    "owners": [],
    "project": {
      "id": "mobile_shopping_app"
    }
  }
}
```

The following policy ensures that production environments require approvals and have at least one approver configured.

```rego
package fme_environments

deny[msg] {
  input.fmeEnvironment.environmentType == "production"
  not input.fmeEnvironment.changeSettings.areApprovalsRequired
  msg := sprintf(
    "FME production environment '%s' must have approvals required",
    [input.fmeEnvironment.name]
  )
}

deny[msg] {
  input.fmeEnvironment.environmentType == "production"
  count(object.get(input.fmeEnvironment.changeSettings, "approvers", [])) == 0
  msg := sprintf(
    "FME production environment '%s' must have at least one approver configured",
    [input.fmeEnvironment.name]
  )
}
```

Go to [FME environment policies](https://developer.harness.io/harness-platform/use-harness-platform/governance/policy-as-code/sample-policy-use-case#fme-environment-policies) to view more examples.

</details>

<details>

<summary>Segment</summary>

```json
{
  "fmeSegment": {
    "name": "beta_users",
    "description": "Users enrolled in the beta program",
    "segmentType": "standard_segment",
    "status": "active",
    "tags": [
      "beta",
      "testing"
    ],
    "trafficType": {
      "id": "tt_user_001",
      "name": "user"
    }
  },
  "entityMetadata": {
    "actor": {
      "id": "2PeIU7FK...",
      "type": "user"
    },
    "changeTrigger": "create",
    "owners": [
      {
        "id": "_project_all_users",
        "ownerId": "_project_all_users",
        "ownerType": "team"
      }
    ],
    "project": {
      "id": "mobile_shopping_app"
    },
    "trafficType": {
      "id": "c8bcb9e0-dc3e-...",
      "name": "user"
    }
  }
}
```

The following policy enforces naming conventions for segments.

```rego
package fme_segments

deny[msg] {
  not regex.match("^[a-z][a-z0-9_]*$", input.fmeSegment.name)
  msg := sprintf(
    "FME Segment name '%s' must start with a lowercase letter and contain only lowercase letters, numbers, and underscores",
    [input.fmeSegment.name]
  )
}
```

Go to [FME segment policies](https://developer.harness.io/harness-platform/use-harness-platform/governance/policy-as-code/sample-policy-use-case#fme-segment-policies) to view more examples.

</details>

<details>

<summary>Segment Definition</summary>

**Standard segment definition**

```json
{
  "fmeSegmentDefinition": {
    "id": "105e1764-c07d-...",
    "name": "beta_users",
    "description": "Users enrolled in the beta program",
    "segmentType": "standard_segment",
    "addingKeyCount": 1,
    "currentKeyCount": 10,
    "environment": {
      "name": "Production",
      "type": "production"
    },
    "status": "active",
    "trafficType": {
      "id": "tt_user_001",
      "name": "user"
    }
  },
  "context": {
    "pipelineExecution": {
      "pipelineIdentifier": "fme_change_pipeline",
      "executionId": "exec_01HXYZABCDEFGHJKLMNPQRST"
    }
  },
  "entityMetadata": {
    "actor": {
      "id": "2PeIU7FK...",
      "type": "user"
    },
    "changeTrigger": "update",
    "owners": [],
    "project": {
      "id": "mobile_shopping_app"
    },
    "trafficType": {
      "id": "c8bcb9e0-dc3e-...",
      "name": "user"
    }
  }
}
```

**Large segment definition**

```json
{
  "fmeSegmentDefinition": {
    "name": "eu_users",
    "segmentType": "large_segment",
    "environment": {
      "name": "Production",
      "type": "production"
    },
    "status": "active",
    "trafficType": {
      "id": "tt_user_001",
      "name": "user"
    }
  },
  "context": {
    "pipelineExecution": {
      "pipelineIdentifier": "fme_change_pipeline",
      "executionId": "exec_01HXYZABCDEFGHJKLMNPQRST"
    }
  },
  "entityMetadata": {
    "actor": {
      "id": "2PeIU7FK...",
      "type": "user"
    },
    "changeTrigger": "create",
    "owners": [],
    "project": {
      "id": "mobile_shopping_app"
    },
    "trafficType": {
      "id": "c8bcb9e0-dc3e-...",
      "name": "user"
    }
  }
}
```

**Rule-based segment definition**

```json
{
  "fmeSegmentDefinition": {
    "name": "users_by_country",
    "description": "",
    "segmentType": "rule_based_segment",
    "definition": [
      {
        "condition": {
          "combiner": "AND",
          "matchers": [
            {
              "attribute": "country",
              "strings": [
                "US",
                "AR"
              ],
              "type": "IN_LIST_STRING"
            }
          ]
        }
      }
    ],
    "environment": {
      "name": "Production",
      "type": "production"
    },
    "excludedKeys": [],
    "excludedSegments": [
      {
        "name": "high_priority_users",
        "type": "standard_segment"
      }
    ],
    "status": "active",
    "trafficType": {
      "id": "c8bcb9e0-dc3e-...",
      "name": "user"
    }
  },
  "context": {
    "pipelineExecution": {
      "pipelineIdentifier": "fme_change_pipeline",
      "executionId": "exec_01HXYZABCDEFGHJKLMNPQRST"
    }
  },
  "entityMetadata": {
    "actor": {
      "id": "2PeIU7FK...",
      "type": "user"
    },
    "changeTrigger": "update",
    "owners": [],
    "project": {
      "id": "mobile_shopping_app"
    },
    "trafficType": {
      "id": "c8bcb9e0-dc3e-...",
      "name": "user"
    }
  }
}
```

The following policy restricts a standard segment to no more than 100 keys.

```rego
package fme_segment_definitions

resulting_count := (
    object.get(input.fmeSegmentDefinition, "currentKeyCount", 0) +
    object.get(input.fmeSegmentDefinition, "addingKeyCount", 0) -
    object.get(input.fmeSegmentDefinition, "removingKeyCount", 0)
)

deny[msg] {
  input.fmeSegmentDefinition.segmentType == "standard_segment"
  input.fmeSegmentDefinition.addingKeyCount
  resulting_count > 100
  msg := sprintf("Segment '%s' would have %v keys after this change, which is above the maximum allowed of 100", [input.fmeSegmentDefinition.name, resulting_count])
}
```

Go to [FME segment definition policies](https://developer.harness.io/harness-platform/use-harness-platform/governance/policy-as-code/sample-policy-use-case#fme-segment-definition-policies) to view more examples.

</details>

The payload examples earlier on this page are simplified for readability. To view the full input payload for your policy evaluation, add your policy to a policy set and trigger its evaluation. Then, on the **Policies** page, select the **Evaluations** tab, select the evaluation, expand the policy set, and select the link to the policy evaluation. The full input payload appears in the left panel. When you edit a policy, you can select the same input payload by selecting **Select Input** on the Edit Policy page.

***

## Troubleshooting

The following issues are the most common reasons a policy does not behave as expected.

<details>

<summary>The policy never appears on the Evaluations tab</summary>

A policy is evaluated only when it belongs to a policy set that is enforced. Check that the policy set has the **Enforced** checkbox selected in the **Policy Sets** list, that its trigger event is **On Save**, and that its entity type matches the entity you changed.

</details>

<details>

<summary>The policy is evaluated but never reports a violation</summary>

The entity type of the policy set decides which payload each policy receives. If a policy reads `input.featureFlag` but sits in an **FME Feature Flag Definition** policy set, the field does not exist, the `deny` rule is undefined, and the policy always passes. Move the policy to a policy set of the matching entity type. Use **Select Input** in the **Testing Terminal** to test it against a real payload.

</details>

<details>

<summary>Existing entities violate a new policy but nothing fails</summary>

Policies do not apply retroactively. An existing entity is evaluated the next time it is created, updated, deleted, or archived. To evaluate it now, save it again.

</details>

<details>

<summary>A naming or metadata policy blocks deleting or archiving old entities</summary>

The policy runs on every change, including `delete` and `archive`. Add a condition such as `input.entityMetadata.changeTrigger != "delete"` to the rule so that cleanup is not blocked. Go to the **Feature Flag** example in the [input payload reference](#input-payload-reference) for a working policy.

</details>

<details>

<summary>A change was saved even though the policy reported a violation</summary>

The policy is set to **Warn and Continue** in its policy set, which records a warning but saves the change. To block the change, edit the policy set and set the policy to **Error and Exit**.

</details>

***

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

After you configure policies, use the following resources.

* [Harness Policy As Code overview](https://developer.harness.io/harness-platform/use-harness-platform/governance/policy-as-code/harness-governance-overview): Review policy concepts and enforcement.
* [Harness Policy As Code quickstart](https://developer.harness.io/harness-platform/use-harness-platform/governance/policy-as-code/harness-governance-quickstart): Create and enforce a first policy.
* [FME Feature Flag policy samples](https://developer.harness.io/harness-platform/use-harness-platform/governance/policy-as-code/sample-policy-use-case#fme-feature-flag-policies): Review sample Rego for feature flags.
* [FME Feature Flag Definition policy samples](https://developer.harness.io/harness-platform/use-harness-platform/governance/policy-as-code/sample-policy-use-case#fme-feature-flag-definition-policies): Review sample Rego for feature flag definitions.
* [FME pipelines](/feature-management-experimentation/management-and-administration/pipelines.md): Run FME changes in pipelines that these policies govern.
* [Configure Git Experience for OPA](https://developer.harness.io/harness-platform/use-harness-platform/governance/policy-as-code/configure-gitexperience-for-opa): Store policies in a Git repository.

{% @harness-feedback/feedback %}
