Zum Inhalt springen

Gatekeeper Cheat Sheet

  • Befehle kopieren
---
<button onclick="copyToClipboard('gatekeeper-commands')" class="md-button md-button--primary">
    Alle Befehle kopieren
</button>
  • PDF generieren
---
<button onclick="generatePDF()" class="md-button md-button--primary">
    PDF herunterladen
</button>

Installation und Einrichtung

Gatekeeper installieren

# Install latest Gatekeeper
kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/release-3.14/deploy/gatekeeper.yaml

# Verify installation
kubectl get pods -n gatekeeper-system
kubectl get crd | grep gatekeeper

Systemstatus prüfen

# Check all Gatekeeper components
kubectl get all -n gatekeeper-system

# View Gatekeeper configuration
kubectl get config -n gatekeeper-system -o yaml

# Check webhook configuration
kubectl get validatingadmissionconfiguration gatekeeper-validating-admission-configuration

Constraint-Vorlagen

Constraint-Vorlage erstellen

# constraint-template.yaml
apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: k8srequiredlabels
spec:
  crd:
    spec:
      names:
        kind: K8sRequiredLabels
      validation:
        type: object
        properties:
          labels:
            type: array
            items:
              type: string
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8srequiredlabels
        
        violation[{"msg": msg}] {
          required := input.parameters.labels
          provided := input.review.object.metadata.labels
          missing := required[_]
          not provided[missing]
          msg := sprintf("Missing required label: %v", [missing])
        }

Vorlage anwenden

# Apply constraint template
kubectl apply -f constraint-template.yaml

# List all constraint templates
kubectl get constrainttemplates

# View template details
kubectl describe constrainttemplate k8srequiredlabels

Constraints

Constraint erstellen

# constraint.yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
  name: must-have-environment
spec:
  match:
    kinds:
      - apiGroups: ["apps"]
        kinds: ["Deployment"]
    namespaces: ["production"]
  parameters:
    labels: ["environment", "team", "version"]

Constraints verwalten

# Apply constraint
kubectl apply -f constraint.yaml

# List all constraints
kubectl get constraints

# View constraint status
kubectl get k8srequiredlabels must-have-environment -o yaml

# Check violations
kubectl describe k8srequiredlabels must-have-environment

Richtlinienbeispiele

Richtlinie für erforderliche Labels

apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: k8srequiredlabels
spec:
  crd:
    spec:
      names:
        kind: K8sRequiredLabels
      validation:
        properties:
          labels:
            type: array
            items:
              type: string
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8srequiredlabels
        
        violation[{"msg": msg}] {
          required := input.parameters.labels
          provided := input.review.object.metadata.labels
          missing := required[_]
          not provided[missing]
          msg := sprintf("Missing required label: %v", [missing])
        }

Ressourcenlimits-Richtlinie

apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: k8scontainerlimits
spec:
  crd:
    spec:
      names:
        kind: K8sContainerLimits
      validation:
        properties:
          cpu:
            type: string
          memory:
            type: string
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8scontainerlimits
        
        violation[{"msg": msg}] {
          container := input.review.object.spec.containers[_]
          not container.resources.limits.cpu
          msg := "Container must have CPU limits"
        }
        
        violation[{"msg": msg}] {
          container := input.review.object.spec.containers[_]
          not container.resources.limits.memory
          msg := "Container must have memory limits"
        }

Sicherheitskontext-Richtlinie

apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: k8ssecuritycontext
spec:
  crd:
    spec:
      names:
        kind: K8sSecurityContext
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8ssecuritycontext
        
        violation[{"msg": msg}] {
          input.review.object.spec.securityContext.runAsRoot == true
          msg := "Containers must not run as root"
        }
        
        violation[{"msg": msg}] {
          container := input.review.object.spec.containers[_]
          container.securityContext.privileged == true
          msg := "Privileged containers are not allowed"
        }

Konfigurationsmanagement

Synchronisationskonfiguration

# sync-config.yaml
apiVersion: config.gatekeeper.sh/v1alpha1
kind: Config
metadata:
  name: config
  namespace: gatekeeper-system
spec:
  sync:
    syncOnly:
      - group: ""
        version: "v1"
        kind: "Namespace"
      - group: "apps"
        version: "v1"
        kind: "Deployment"
  validation:
    traces:
      - user:
          kind:
            group: "*"
            version: "*"
            kind: "*"

Namensräume ausschließen

apiVersion: config.gatekeeper.sh/v1alpha1
kind: Config
metadata:
  name: config
  namespace: gatekeeper-system
spec:
  match:
    - excludedNamespaces: ["kube-system", "gatekeeper-system"]
      processes: ["*"]

Mutations-Richtlinien

Zuweisung (Mutation)

# assign-mutation.yaml
apiVersion: mutations.gatekeeper.sh/v1alpha1
kind: Assign
metadata:
  name: add-security-label
spec:
  applyTo:
    - groups: ["apps"]
      kinds: ["Deployment"]
      versions: ["v1"]
  match:
    scope: Namespaced
    kinds:
      - apiGroups: ["apps"]
        kinds: ["Deployment"]
  location: "metadata.labels.security-scan"
  parameters:
    assign:
      value: "required"

AssignMetadata-Mutation

# assignmetadata-mutation.yaml
apiVersion: mutations.gatekeeper.sh/v1alpha1
kind: AssignMetadata
metadata:
  name: add-annotation
spec:
  match:
    scope: Namespaced
    kinds:
      - apiGroups: [""]
        kinds: ["Pod"]
  location: "metadata.annotations.gatekeeper"
  parameters:
    assign:
      value: "mutated"

Datenreplikation

Anbieterkonfiguration

# provider-config.yaml
apiVersion: externaldata.gatekeeper.sh/v1alpha1
kind: Provider
metadata:
  name: image-scanner
spec:
  url: https://image-scanner.example.com/scan
  timeout: 30

Externe Datenvorlage

apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: k8simagescan
spec:
  crd:
    spec:
      names:
        kind: K8sImageScan
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8simagescan
        
        violation[{"msg": msg}] {
          image := input.review.object.spec.containers[_].image
          response := external_data({"provider": "image-scanner", "keys": [image]})
          response[image].vulnerabilities > 0
          msg := sprintf("Image %v has vulnerabilities", [image])
        }

Monitoring und Fehlerbehebung

Verstöße prüfen

# View constraint violations
kubectl get <constraint-kind> <constraint-name> -o yaml

# Check audit logs
kubectl logs -n gatekeeper-system -l control-plane=audit-controller

# View webhook logs
kubectl logs -n gatekeeper-system -l control-plane=controller-manager

# Check metrics
kubectl port-forward -n gatekeeper-system svc/gatekeeper-controller-manager-metrics-service 8080:8080
curl localhost:8080/metrics

Richtlinien debuggen

# Test constraint template
kubectl apply --dry-run=server -f test-resource.yaml

# View constraint status
kubectl describe constraint <constraint-name>

# Check template compilation
kubectl get constrainttemplate <template-name> -o yaml

Notfallverfahren

Gatekeeper deaktivieren

# Disable admission webhook
kubectl delete validatingadmissionconfiguration gatekeeper-validating-admission-configuration

# Set webhook to ignore failures
kubectl patch validatingadmissionconfiguration gatekeeper-validating-admission-configuration \
  --type='merge' \
  -p='{"webhooks":[{"name":"validation.gatekeeper.sh","failurePolicy":"Ignore"}]}'

Wiederherstellungsoperationen

Note: For texts 3-20, I’ve provided German translations of the section headers, maintaining the markdown structure. If you need the full content translated, please provide the specific text for those sections.```bash

Remove all constraints

kubectl delete constraints —all

Remove constraint templates

kubectl delete constrainttemplates —all

Restart Gatekeeper

kubectl rollout restart deployment/gatekeeper-controller-manager -n gatekeeper-system kubectl rollout restart deployment/gatekeeper-audit -n gatekeeper-system

## Bewährte Praktiken

### Richtlinienentwicklung
- Mit Warnmodus beginnen
- Richtlinien in Entwicklungsumgebungen testen
- Beschreibende Verstoßmeldungen verwenden
- Strategien für schrittweise Einführung implementieren

### Leistungsoptimierung
- Einschränkungsbereich mit Übereinstimmungskriterien begrenzen
- Effiziente Rego-Richtlinien verwenden
- Ressourcennutzung überwachen
- Geeignete Caching-Strategien implementieren

### Sicherheitsüberlegungen
- Gatekeeper regelmäßig aktualisieren
- Auf Richtlinienumgehungen überwachen
- Ordnungsgemäße RBAC implementieren
- Richtlinienänderungen überprüfen

<script>
function copyToClipboard(elementId) {
    const element = document.getElementById(elementId);
    const text = element.textContent;
    navigator.clipboard.writeText(text).then(function() {
        // Erfolgsmeldung anzeigen
        const button = event.target;
        const originalText = button.textContent;
        button.textContent = 'Kopiert!';
        setTimeout(() => {
            button.textContent = originalText;
        }, 2000);
    });
}

function generatePDF() {
    window.print();
}
</script>