Kustomize
__HTML_TAG_93_ _
__HTML_TAG_93_ _
Kustomize Cheatsheet
| 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 |
| 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 |
| 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 |
__TABLE_103_
__TABLE_104_
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
# 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
# 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"
# 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"
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"
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
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/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
# 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
# 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 .
# 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 -
# 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 .
# 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
Hable name suffix hashing for ConfigMaps/Secrets: Esto activa la cápsula cuando cambia la configuración, asegurando que las aplicaciones recojan nuevos configs automáticamente (disableNameSuffixHash: false)
Organizar la estructura del directorio lógicamente: Use una jerarquía clara como base/, overlays/dev/, overlays/production/, y __INLINE_CODE_67 para hacer el repositorio fácil de navegar y entender
Utilice parches estratégicos para cambios simples: Preferir patchesStrategicMerge_ sobre parches JSON para legibilidad y mantenimiento al realizar modificaciones directas a los recursos
El control de la versión todo Comprobar todos los archivos de kustomización, parches y manifiestos a Git para la trazabilidad completa, la capacidad de devolución y los flujos de trabajo de GitOps
Validar antes de aplicar: Siempre ejecutar kustomize build . | kubectl apply --dry-run=server -f -_ para capturar errores y validar recursos contra el esquema OpenAPI del cluster antes del despliegue real
Utilizar componentes para funciones opcionales: Crear componentes reutilizables para preocupaciones transversales como monitoreo, registro o políticas de seguridad que pueden incluirse opcionalmente en diferentes superposiciones
Mantenga parches enfocados y mínimos: Crear pequeños parches dirigidos que modifiquen sólo lo necesario en lugar de duplicar definiciones completas de recursos
Use reemplazos en lugar de vars: Preferir el nuevo campo replacements sobre el campo deprecated vars para referencias de sustitución variable y de recursos cruzados
Documente su estructura de kustomización: Añadir comentarios en kustomization. archivos yaml y mantener un README explicando la estrategia de superposición y cómo desplegarse en diferentes entornos
| 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 |
-...
** Consejos de referencia rápidos:**
kubectl apply -k . en lugar de kustomize build . | kubectl apply -f - para despliegues más sencillos--dry-run=client -o yaml para previsualizar cambios sin acceso a clústerkustomize cfg tree para visualizar las relaciones de recursos y las dependenciasKUSTOMIZE_PLUGIN_HOME variable entorno para ubicaciones de plugin personalizadaskustomize config help