Zum Inhalt
_

Kustomize Cheatsheet

• Installation

Platform Command
kubectl (built-in) INLINE_CODE_14 (v1.14+, no installation needed)
macOS (Homebrew) INLINE_CODE_15
Linux (curl) INLINE_CODE_16
Windows (Chocolatey) INLINE_CODE_17
Windows (Scoop) INLINE_CODE_18
Docker INLINE_CODE_19
Verify Installation INLINE_CODE_20 or INLINE_CODE_21

oder Grundlegende Befehle

Command Description
INLINE_CODE_22 Generate customized YAML from current directory
INLINE_CODE_23 Build using kubectl's integrated kustomize
INLINE_CODE_24 Build and apply manifests directly to cluster
INLINE_CODE_25 Build and save output to file
INLINE_CODE_26 Create a new kustomization.yaml file
INLINE_CODE_27 Create kustomization.yaml with auto-detected resources
INLINE_CODE_28 Create kustomization.yaml with specified namespace
INLINE_CODE_29 Add a resource to kustomization.yaml
INLINE_CODE_30 Add a base directory reference
INLINE_CODE_31 Set the namespace for all resources
INLINE_CODE_32 Add prefix to all resource names
INLINE_CODE_33 Add suffix to all resource names
INLINE_CODE_34 Add common labels to all resources
INLINE_CODE_35 Add common annotations to all resources
INLINE_CODE_36 Validate manifests without applying

ConfigMap und Secret Management

Command Description
INLINE_CODE_37 Create ConfigMap from literal values
INLINE_CODE_38 Create ConfigMap from file
INLINE_CODE_39 Create ConfigMap from environment file
INLINE_CODE_40 Create Secret from literal values
INLINE_CODE_41 Create Secret from files
INLINE_CODE_42 Create ConfigMap with merge behavior
INLINE_CODE_43 Create ConfigMap without hash suffix

Bildverwaltung

Command Description
INLINE_CODE_44 Update image tag for a container
INLINE_CODE_45 Update image with full registry path
INLINE_CODE_46 Update multiple images simultaneously
INLINE_CODE_47 Set image to latest tag

/ Fortgeschrittene Nutzung

Command Description
INLINE_CODE_48 Set replica count for specific deployment
INLINE_CODE_49 Add a strategic merge patch file
INLINE_CODE_50 Add inline JSON patch
INLINE_CODE_51 Build from specific overlay directory
INLINE_CODE_52 Build with alpha plugin support enabled
INLINE_CODE_53 Build without load restrictions
INLINE_CODE_54 Build with legacy resource ordering
INLINE_CODE_55 Build with specific output file
INLINE_CODE_56 Search for resources by kind
INLINE_CODE_57 Count resources in kustomization
INLINE_CODE_58 Display resource tree structure
INLINE_CODE_59 Add reusable component to overlay
INLINE_CODE_60 Add Custom Resource Definition
INLINE_CODE_61 Add custom transformer
INLINE_CODE_62 Server-side validation before applying

Konfiguration

Basic kustomization. Yaml Struktur

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

# Resources to include
resources:
  - deployment.yaml
  - service.yaml
  - configmap.yaml

# Namespace for all resources
namespace: production

# Common labels applied to all resources
commonLabels:
  app: myapp
  environment: prod

# Common annotations applied to all resources
commonAnnotations:
  managed-by: kustomize
  version: "1.0.0"

# Name prefix/suffix
namePrefix: prod-
nameSuffix: -v1

# Images to replace
images:
  - name: myapp
    newName: gcr.io/myproject/myapp
    newTag: v2.0.0

# Replica counts
replicas:
  - name: myapp-deployment
    count: 3

Overlay Structure with Base

# overlays/production/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

# Reference to base
bases:
  - ../../base

# Production-specific namespace
namespace: production

# Production-specific patches
patchesStrategicMerge:
  - deployment-patch.yaml
  - service-patch.yaml

# Production replicas
replicas:
  - name: myapp
    count: 5

# Production images
images:
  - name: myapp
    newTag: v2.0.0

Strategische Verschmelzung Patch Beispiel

# deployment-patch.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp
spec:
  template:
    spec:
      containers:
        - name: myapp
          resources:
            limits:
              memory: "2Gi"
              cpu: "1000m"
            requests:
              memory: "1Gi"
              cpu: "500m"
          env:
            - name: ENVIRONMENT
              value: "production"

JSON Patch Beispiel

# kustomization.yaml with JSON patches
patchesJson6902:
  - target:
      group: apps
      version: v1
      kind: Deployment
      name: myapp
    patch: |-
      - op: replace
        path: /spec/replicas
        value: 5
      - op: add
        path: /spec/template/spec/containers/0/env/-
        value:
          name: NEW_VAR
          value: "new_value"

ConfigMap Generator

configMapGenerator:
  - name: app-config
    files:
      - application.properties
      - config.json
    literals:
      - ENVIRONMENT=production
      - LOG_LEVEL=info
    behavior: create  # create, replace, or merge
    options:
      disableNameSuffixHash: false
      labels:
        app: myapp
      annotations:
        config-version: "1.0"

Secret Generator

secretGenerator:
  - name: db-credentials
    literals:
      - username=admin
      - password=secretpassword
    type: Opaque
  - name: tls-secret
    files:
      - tls.crt=cert.pem
      - tls.key=key.pem
    type: kubernetes.io/tls

Ersetzen (Variable Substitution)

replacements:
  - source:
      kind: ConfigMap
      name: app-config
      fieldPath: data.app_version
    targets:
      - select:
          kind: Deployment
        fieldPaths:
          - spec.template.metadata.labels.version
      - select:
          kind: Service
        fieldPaths:
          - metadata.annotations.[app.version]

Komponenten (Reusable Configuration)

# components/monitoring/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1alpha1
kind: Component

resources:
  - servicemonitor.yaml
  - prometheusrule.yaml

labels:
  - pairs:
      monitoring: enabled
# Using component in overlay
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

resources:
  - ../../base

components:
  - ../../components/monitoring
  - ../../components/logging

Häufige Anwendungsfälle

Use Case 1: Multi-Environment Deployment

# Directory structure
# .
# ├── base/
# │   ├── kustomization.yaml
# │   ├── deployment.yaml
# │   └── service.yaml
# ├── overlays/
# │   ├── dev/
# │   │   └── kustomization.yaml
# │   ├── staging/
# │   │   └── kustomization.yaml
# │   └── production/
# │       └── kustomization.yaml

# Create base
cd base
kustomize create --autodetect
kustomize edit add label app:myapp

# Create dev overlay
cd ../overlays/dev
kustomize create
kustomize edit add base ../../base
kustomize edit set namespace dev
kustomize edit set replicas deployment/myapp=1
kustomize edit set image myapp=myapp:dev

# Create production overlay
cd ../production
kustomize create
kustomize edit add base ../../base
kustomize edit set namespace production
kustomize edit set replicas deployment/myapp=5
kustomize edit set image myapp=myapp:v1.0.0

# Deploy to different environments
kubectl apply -k overlays/dev
kubectl apply -k overlays/staging
kubectl apply -k overlays/production

Use Case 2: Hinzufügen von Geheimnissen und ConfigMaps

# Create base configuration
kustomize create --resources deployment.yaml,service.yaml

# Add ConfigMap from file
kustomize edit add configmap app-config \
  --from-file=application.properties \
  --from-literal=LOG_LEVEL=info

# Add Secret from literals
kustomize edit add secret db-credentials \
  --from-literal=username=admin \
  --from-literal=password=changeme

# Add Secret from files
kustomize edit add secret tls-certs \
  --from-file=tls.crt=./certs/server.crt \
  --from-file=tls.key=./certs/server.key

# Build and verify
kustomize build . | grep -A 10 "kind: ConfigMap"
kustomize build . | grep -A 10 "kind: Secret"

# Apply to cluster
kubectl apply -k .

Use Case 3: Patching Ressourcen für verschiedene Umgebungen

# Create production overlay
mkdir -p overlays/production
cd overlays/production

# Create kustomization
kustomize create
kustomize edit add base ../../base
kustomize edit set namespace production

# Create patch file for resource limits
cat <<EOF > deployment-patch.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp
spec:
  template:
    spec:
      containers:
        - name: myapp
          resources:
            limits:
              memory: "4Gi"
              cpu: "2000m"
            requests:
              memory: "2Gi"
              cpu: "1000m"
EOF

# Add patch to kustomization
kustomize edit add patch --path deployment-patch.yaml

# Add production-specific environment variables
cat <<EOF > env-patch.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp
spec:
  template:
    spec:
      containers:
        - name: myapp
          env:
            - name: ENVIRONMENT
              value: "production"
            - name: DB_HOST
              value: "prod-db.example.com"
EOF

kustomize edit add patch --path env-patch.yaml

# Build and apply
kustomize build . | kubectl apply -f -

Use Case 4: Verwendung von Komponenten für optionale Funktionen

# Create monitoring component
mkdir -p components/monitoring
cd components/monitoring

# Create component kustomization
cat <<EOF > kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1alpha1
kind: Component

resources:
  - servicemonitor.yaml

labels:
  - pairs:
      monitoring.enabled: "true"
EOF

# Create ServiceMonitor resource
cat <<EOF > servicemonitor.yaml
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: myapp
spec:
  selector:
    matchLabels:
      app: myapp
  endpoints:
    - port: metrics
      interval: 30s
EOF

# Use component in production overlay
cd ../../overlays/production
kustomize edit add component ../../components/monitoring

# Build with monitoring enabled
kustomize build .

# Deploy
kubectl apply -k .

Use Case 5: Mehrere Anwendungen verwalten

# Directory structure for multiple apps
# .
# ├── apps/
# │   ├── frontend/
# │   │   ├── base/
# │   │   └── overlays/
# │   ├── backend/
# │   │   ├── base/
# │   │   └── overlays/
# │   └── database/
# │       ├── base/
# │       └── overlays/
# └── clusters/
#     ├── dev/
#     └── production/

# Create cluster-level kustomization for production
cd clusters/production
cat <<EOF > kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

namespace: production

resources:
  - ../../apps/frontend/overlays/production
  - ../../apps/backend/overlays/production
  - ../../apps/database/overlays/production

commonLabels:
  environment: production
  cluster: production-us-east-1
EOF

# Deploy entire production cluster
kubectl apply -k clusters/production

# Deploy only frontend
kubectl apply -k apps/frontend/overlays/production

# Build and review all production resources
kustomize build clusters/production > production-manifests.yaml

oder Best Practices

  • **Unterstützung und Overlay-Muster*: Gemeinsame Konfigurationen in grundlegenden und umweltspezifischen Änderungen in Overlays halten, um DRY-Prinzipien zu verfolgen und die Konsistenz in Umgebungen zu erhalten

  • **Enable name suffix hashing for ConfigMaps/Secrets*: Dies löst Pod-Neustarts bei Änderungen der Konfiguration aus, sodass Anwendungen automatisch neue Configs aufnehmen (disableNameSuffixHash: false)

  • **Organisieren Sie Verzeichnisstruktur logisch*: Verwenden Sie eine klare Hierarchie wie base/, overlays/dev/, overlays/production/ und components/, um das Projektarchiv einfach zu navigieren und zu verstehen

  • ** Verwenden Sie strategische Zusammenführung Patches für einfache Änderungen*: Bevorzugen patchesStrategicMerge über JSON-Patches für Lesbarkeit und Aufrechterhaltungsfähigkeit bei einfachen Änderungen an Ressourcen

  • **Version steuert alles*: Kombinieren Sie alle kustomization Dateien, Patches und manifestiert Git für volle Rückverfolgbarkeit, Rollback-Fähigkeit und GitOps Workflows

  • **Validate vor Bewerbung*: Führen Sie immer kustomize build . | kubectl apply --dry-run=server -f - aus, um Fehler zu erfassen und Ressourcen gegen das OpenAPI-Schema des Clusters vor der tatsächlichen Bereitstellung zu validieren.

  • **Benutze Komponenten für optionale Features*: Erstellen Sie wiederverwendbare Komponenten für Querschnittsbelange wie Überwachung, Protokollierung oder Sicherheitsrichtlinien, die optional in verschiedenen Overlays enthalten sein können

  • Keep Patches konzentriert und minimal: Erstellen Sie kleine, gezielte Patches, die nur das ändern, was nötig ist, anstatt ganze Ressourcendefinitionen zu duplizieren

  • Benutzen Sie Ersatz anstelle von vars: Bestimmen Sie das neuere Feld replacements über deprecated vars für variable Substitution und Cross-Ressource Referenzen

  • **Dokumentieren Sie Ihre Kkustomisierungsstruktur*: Kommentare in kustomization hinzufügen. yaml Dateien und ein README, das die Overlay-Strategie erklärt und wie man in verschiedenen Umgebungen eingesetzt

Fehlerbehebung

Issue Solution
Error: "no matches for kind X in version Y" Ensure your cluster supports the API version. Check with INLINE_CODE_72 or update the resource's INLINE_CODE_73 field
Resources not being patched Verify patch target matches exactly (name, kind, apiVersion). Use INLINE_CODE_74 to inspect output and ensure patches are applied
ConfigMap/Secret changes not triggering pod restart Enable name suffix hashing (INLINE_CODE_75) so resource names change when content changes, forcing pod recreation
"accumulating resources: accumulation err='accumulating resources from '../base': ...'" Check that base path is correct and base directory contains valid INLINE_CODE_76. Use relative paths from overlay directory
Duplicate resource error Remove duplicate entries from resources list or check if resource is included both directly and through a base. Use INLINE_CODE_77 to identify duplicates
Image not being replaced Ensure image name in INLINE_CODE_78 field matches container image name exactly. Use INLINE_CODE_79 command to avoid typos
"json: cannot unmarshal string into Go value" Check YAML syntax in kustomization.yaml. Ensure proper indentation and that list items use INLINE_CODE_80 prefix. Validate with INLINE_CODE_81
Patches not applying in expected order Patches are applied in order listed. Reorder patches in INLINE_CODE_82 or INLINE_CODE_83 arrays to control application sequence
"field X not found in type Y" The field doesn't exist in the resource type. Check Kubernetes API documentation for correct field paths and structure
Namespace not being set on resources Some resources are cluster-scoped (ClusterRole, PersistentVolume). Verify resource kind supports namespaces with INLINE_CODE_84
Remote base not loading Check network connectivity and URL format. For GitHub: INLINE_CODE_85. Ensure repository is public or credentials are configured
Component not being applied Verify component path is correct and component has INLINE_CODE_86. Check that component's kustomization.yaml is valid

--

Quick Referenz-Tipps:

  • Verwenden kubectl apply -k . anstelle von kustomize build . | kubectl apply -f -_ für einfachere Bereitstellungen
  • Fügen Sie __INLINE_CODE_89_ zur Vorschau von Änderungen ohne Clusterzugriff hinzu
  • Verwenden Sie kustomize cfg tree, um Ressourcenbeziehungen und Abhängigkeiten zu visualisieren
  • Set __INLINE_CODE_91_ Umgebungsvariable für benutzerdefinierte Plugin-Standorte
  • Prüfen Sie die integrierte Transformator-Dokumentation: kustomize config help