# Policy as code

Validate, apply, version, and promote .kastra policies with the operator CLI.

Updated: 2026-09-22

Canonical: https://docs.kastra.ai/policies/policy-as-code

## Create a policy file

Install the [operator CLI](https://docs.kastra.ai/reference/cli) and authenticate as an administrator for writes. A `.kastra` file is YAML or JSON representing policy metadata and its rule specification.

```sh
kastra init
kastra policy validate ./policy.kastra
```

A scoped example for an illustrative tool integration:

```yaml
apiVersion: kastra/v1
kind: Policy
metadata:
  name: review-test-tool
  environment: dev
spec:
  default_decision: allow
  deny:
    - reason: Review this test tool
      effect: hold
      trigger: pre_inference
      conditions:
        - attribute: x-kastra-attr-tool
          operator: eq
          value: example_write_tool
```

Replace the illustrative tool name with one actually emitted by your integration. Review HOLD expiry and timeout behavior in the editor before activating.

## Apply without conflating activation

```sh
kastra policy apply ./policy.kastra
kastra policy list
```

`apply` creates or updates the policy by name/environment. Confirm the returned policy ID and revision before activation. Use the explicit `activate` command when ready; a file write or validation pass alone is not proof that the policy is enforcing.

## Review revisions

The CLI supports revision activation, rollback, and environment promotion. Export policy files through the console or the [policy API](https://docs.kastra.ai/reference/management-api#policies). Commands take policy IDs where documented; do not substitute a display name for an ID. Production and destructive operations can ask for confirmation.

```text
kastra policy activate POLICY_ID --revision REVISION_NUMBER
kastra policy rollback POLICY_ID --revision REVISION_NUMBER
kastra policy promote POLICY_ID --to TARGET_ENVIRONMENT
```

These are templates requiring real IDs and reviewed target environments. Validate and replay the candidate before a shared rollout. [Shadow and replay](https://docs.kastra.ai/policies/shadow-replay).
