Kustomize Cheatsheet¶
Installazione¶
Tabella_100_
Comandi di base¶
Tabella_101_
ConfigMap e gestione segreta¶
Tabella_102_
Image Management¶
Tabella_103_
Uso avanzato¶
Tabella_104_
Configurazione¶
Kustomization Basic. Ciao. Struttura¶
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
Strategic Merge Patch Esempio¶
# 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 Esempio¶
# 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
Sostituzioni (sostituzioni variabili)¶
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]
Components (Configurazione riutilizzabile)¶
# 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
Common Use Cases¶
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: Aggiungere segreti e conflitti¶
# 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 Resources for Different Environments¶
# 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: Utilizzo di componenti per funzioni opzionali¶
# 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: Gestione delle applicazioni multiple¶
# 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
Migliori Pratiche¶
-
** Utilizzare la base e sovrapposizioni modello**: Mantenere configurazioni comuni in base e cambiamenti specifici per l'ambiente in sovrapposizioni per seguire i principi DRY e mantenere la coerenza in ambienti
-
Abilitare il suffisso del nome per ConfigMaps/Secrets: Questo trigger pod riavvia quando la configurazione cambia, assicurando che le applicazioni prelevano automaticamente nuove configurazioni (INLINE_CODE_63_)
-
Organizzare la struttura della directory logicamente: Utilizzare una gerarchia chiara come
base/,overlays/dev/,overlays/production/, ecomponents/per rendere il repository facile da navigare e capire -
Utilizzare le patch strategiche per semplici modifiche: Preferire
patchesStrategicMergesu patch JSON per la leggibilità e la manutenbilità quando si effettuano modifiche semplici alle risorse -
Controllo delle vibrazioni. Commettere tutti i file di kustomization, patch e si manifesta a Git per la tracciabilità completa, capacità di rollback e flussi di lavoro GitOps
-
Validate prima di applicare Eseguire sempre
kustomize build . | kubectl apply --dry-run=server -f -per catturare gli errori e convalidare le risorse dallo schema OpenAPI del cluster prima dell'implementazione effettiva -
Utilizza componenti per caratteristiche facoltative: Crea componenti riutilizzabili per problemi di taglio incrociato come monitoraggio, registrazione o politiche di sicurezza che possono essere eventualmente incluse in diversi sovrapposizioni
-
Keep patch concentrati e minimi: Creare piccole patch mirate che modificano solo ciò che è necessario piuttosto che duplicare intere definizioni delle risorse
-
** Utilizzare sostituzioni al posto dei vars**: Preferire il nuovo campo
replacements_ sopra deprecatovarsper sostituzioni variabili e riferimenti cross-resource -
** Documenta la tua struttura di kustomization**: Aggiungi commenti in kustomization. file yaml e mantenere un README spiegando la strategia di sovrapposizione e come distribuire in ambienti diversi
Risoluzione dei problemi¶
Tabella_105_¶
Quick Reference Tips:
- Usa
kubectl apply -k .invece dikustomize build . | kubectl apply -f -per implementazioni più semplici - Aggiungi
--dry-run=client -o yamlper visualizzare in anteprima le modifiche senza accesso a cluster - Usa
kustomize cfg treeper visualizzare le relazioni e le dipendenze delle risorse - Set
KUSTOMIZE_PLUGIN_HOMEvariabili di ambiente per posizioni di plugin personalizzate - Controllare la documentazione del trasformatore incorporato: ______________