# Opa Policies

> Write OPA/Gatekeeper and Kyverno admission policies for Kubernetes security guardrails.

- **Type:** Skill
- **Install:** `agentstack add skill-sawrus-agent-guides-opa-policies`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [sawrus](https://agentstack.voostack.com/s/sawrus)
- **Installs:** 0
- **Category:** [Cloud & Infrastructure](https://agentstack.voostack.com/c/cloud-infrastructure)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [sawrus](https://github.com/sawrus)
- **Source:** https://github.com/sawrus/agent-guides/tree/main/areas/devops/devsecops/skills/opa-policies
- **Website:** https://sawrus.github.io/agent-guides

## Install

```sh
agentstack add skill-sawrus-agent-guides-opa-policies
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# Skill: OPA Policies & Kyverno

> **Expertise:** Gatekeeper ConstraintTemplates, Kyverno ClusterPolicies, validation + mutation + generation.

## When to load

When writing admission policies, testing policy changes, or debugging policy-blocked deployments.

## Gatekeeper: ConstraintTemplate + Constraint

```yaml
# 1. ConstraintTemplate — defines the policy logic in Rego
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8srequirenonroot
spec:
  crd:
    spec:
      names: { kind: K8sRequireNonRoot }
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8srequirenonroot

        violation[{"msg": msg}] {
          container := input.review.object.spec.containers[_]
          not container.securityContext.runAsNonRoot
          msg := sprintf("Container '%v' must set runAsNonRoot: true", [container.name])
        }

        violation[{"msg": msg}] {
          container := input.review.object.spec.containers[_]
          container.securityContext.runAsUser == 0
          msg := sprintf("Container '%v' must not run as UID 0", [container.name])
        }

---
# 2. Constraint — applies the template to specific resources/namespaces
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequireNonRoot
metadata:
  name: require-non-root-production
spec:
  enforcementAction: deny           # deny | warn | dryrun
  match:
    kinds:
      - apiGroups: [apps]
        kinds: [Deployment, StatefulSet, DaemonSet]
    namespaceSelector:
      matchExpressions:
        - key: environment
          operator: In
          values: [production, staging]
```

## Gatekeeper: Require Image Digest

```yaml
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8srequireimagedigest
spec:
  crd:
    spec:
      names: { kind: K8sRequireImageDigest }
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8srequireimagedigest

        violation[{"msg": msg}] {
          container := input.review.object.spec.containers[_]
          not contains(container.image, "@sha256:")
          msg := sprintf(
            "Container '%v' image '%v' must reference a digest (@sha256:...), not a mutable tag",
            [container.name, container.image]
          )
        }
```

## Kyverno: Simpler YAML Policies

```yaml
# Disallow privileged containers (Kyverno)
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: disallow-privileged-containers
spec:
  validationFailureAction: Enforce
  rules:
    - name: check-privileged
      match:
        any:
          - resources:
              kinds: [Pod]
              namespaces: [production, staging]
      validate:
        message: "Privileged containers are not allowed in production/staging"
        pattern:
          spec:
            containers:
              - =(securityContext):
                  =(privileged): "false"
```

```yaml
# Kyverno MUTATION — auto-add security context defaults
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: add-default-securitycontext
spec:
  rules:
    - name: add-security-context
      match:
        any:
          - resources: { kinds: [Pod] }
      mutate:
        patchStrategicMerge:
          spec:
            containers:
              - (name): "*"
                securityContext:
                  +(runAsNonRoot): true
                  +(allowPrivilegeEscalation): false
                  +(readOnlyRootFilesystem): true
```

## Policy Testing

```bash
# OPA unit tests
cat > policies/test_nonroot.rego  | grep "denied\|violated"
```

## Debugging Policy Denials

```bash
# See why a deployment was rejected
kubectl describe deploy  -n 
# Look at Events section for: "admission webhook ... denied"

# Check active constraints
kubectl get constraints

# Check constraint violations (audit mode)
kubectl get k8srequirenonroot.constraints.gatekeeper.sh -o jsonpath='{.items[*].status.violations}'
```

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [sawrus](https://github.com/sawrus)
- **Source:** [sawrus/agent-guides](https://github.com/sawrus/agent-guides)
- **License:** MIT
- **Homepage:** https://sawrus.github.io/agent-guides

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-sawrus-agent-guides-opa-policies
- Seller: https://agentstack.voostack.com/s/sawrus
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
