Policy as code allows you to define, version, and enforce security policies declaratively. Two popular tools for Kubernetes are OPA Gatekeeper and Kyverno.

OPA Gatekeeper

Gatekeeper uses Open Policy Agent with Rego policies.

Installation

BASH
kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/deploy/gatekeeper.yaml
Click to expand and view more

Creating Constraints

First, define a template:

YAML
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8srequiredlabels
spec:
  crd:
    spec:
      names:
        kind: K8sRequiredLabels
      validation:
        openAPIV3Schema:
          properties:
            labels:
              type: array
              items:
                type: string
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8srequiredlabels
        violation[{"msg": msg}] {
          provided := {label | input.review.object.metadata.labels[label]}
          required := {label | label := input.parameters.labels[_]}
          missing := required - provided
          count(missing) > 0
          msg := sprintf("Missing labels: %v", [missing])
        }
Click to expand and view more

Then create a constraint:

YAML
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
  name: require-team-label
spec:
  match:
    kinds:
    - apiGroups: [""]
      kinds: ["Namespace"]
  parameters:
    labels: ["team", "environment"]
Click to expand and view more

Kyverno

Kyverno uses Kubernetes-native YAML for policies.

Installation

BASH
kubectl create -f https://github.com/kyverno/kyverno/releases/latest/download/install.yaml
Click to expand and view more

Example Policies

YAML
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: require-requests-limits
spec:
  validationFailureAction: Enforce
  rules:
  - name: validate-resources
    match:
      resources:
        kinds:
        - Pod
    validate:
      message: "CPU and memory requests/limits are required"
      pattern:
        spec:
          containers:
          - resources:
              requests:
                memory: "?*"
                cpu: "?*"
              limits:
                memory: "?*"
                cpu: "?*"
Click to expand and view more

Comparison

FeatureGatekeeperKyverno
LanguageRegoYAML
Learning CurveSteeperGentler
MutationLimitedFull
GenerationNoYes

Essential Policies

  1. Require resource limits
  2. Deny privileged containers
  3. Require labels
  4. Restrict image registries
  5. Enforce network policies

Policy as code brings consistency and auditability to security enforcement.

Start searching

Enter keywords to search articles

↑↓
ESC
⌘K Shortcut