Kustomize
После урока вы сможете
- Собрать base + overlays для dev/prod
- Использовать generators ConfigMap/Secret и распространённые transformers
- Сравнить Kustomize с Helm и выбрать инструмент под задачу
Идея
app/
base/
kustomization.yaml
deployment.yaml
service.yaml
overlays/
dev/
kustomization.yaml
patch-replicas.yaml
prod/
kustomization.yaml
patch-replicas.yaml
kubectl kustomize app/overlays/dev
kubectl apply -k app/overlays/prod
kubectl apply -k app/overlays/prod
Base
base/deployment.yaml:
apiVersion: apps/v1
kind: Deployment
metadata:
name: api
labels:
app: api
spec:
replicas: 1
selector:
matchLabels:
app: api
template:
metadata:
labels:
app: api
spec:
containers:
- name: api
image: ghcr.io/example/api:1.0.0
ports:
- containerPort: 8080
resources:
requests:
cpu: 100m
memory: 128Mi
base/service.yaml:
apiVersion: v1
kind: Service
metadata:
name: api
spec:
selector:
app: api
ports:
- port: 80
targetPort: 8080
base/kustomization.yaml:
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- deployment.yaml
- service.yaml
commonLabels:
app.kubernetes.io/name: api
app.kubernetes.io/part-of: shop
kubectl kustomize app/base
Overlay prod
overlays/prod/kustomization.yaml:
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: shop-prod
resources:
- ../../base
namePrefix: prod-
images:
- name: ghcr.io/example/api
newTag: "1.4.2"
replicas:
- name: api
count: 3
patches:
- path: patch-resources.yaml
- path: patch-ingress.yaml
configMapGenerator:
- name: api-config
literals:
- APP_ENV=production
- LOG_LEVEL=info
secretGenerator:
- name: api-secrets
literals:
- DATABASE_PASSWORD=change-me
type: Opaque
overlays/prod/patch-resources.yaml:
apiVersion: apps/v1
kind: Deployment
metadata:
name: api
spec:
template:
spec:
containers:
- name: api
resources:
requests:
cpu: 200m
memory: 256Mi
limits:
cpu: "1"
memory: 512Mi
envFrom:
- configMapRef:
name: api-config
- secretRef:
name: api-secrets
overlays/prod/patch-ingress.yaml:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: api
spec:
ingressClassName: traefik
rules:
- host: api.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: api
port:
number: 80
Но Ingress нужно добавить в resources overlay или base:
# overlays/prod/kustomization.yaml — дополнение
resources:
- ../../base
- ingress.yaml
Overlay dev
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: shop-dev
resources:
- ../../base
namePrefix: dev-
images:
- name: ghcr.io/example/api
newTag: "1.4.2-rc.1"
replicas:
- name: api
count: 1
configMapGenerator:
- name: api-config
literals:
- APP_ENV=development
- LOG_LEVEL=debug
kubectl apply -k app/overlays/dev
kubectl apply -k app/overlays/prod
kubectl get deploy -A | grep api
Generators
configMapGenerator / secretGenerator
Генерируют объекты и добавляют hash к имени, чтобы изменить Deployment при смене конфига (если включён transformer).
configMapGenerator:
- name: nginx-conf
files:
- nginx.conf
- name: env
envs:
- .env.nonsecret
secretGenerator:
- name: regcred
files:
- .dockerconfigjson
type: kubernetes.io/dockerconfigjson
generatorOptions:
disableNameSuffixHash: false
labels:
generated: "true"
kubectl kustomize overlays/prod | grep -E 'name: api-config|name: api-secrets'
Чтобы Deployment подхватил новое имя ConfigMap:
# в base deployment изначально ссылается на api-config
# kustomize nameReference / встроенное поведение generator обновит ссылки
Отключить hash (редко нужно):
generatorOptions:
disableNameSuffixHash: true
Ресурс из URL / git (осторожно)
resources:
- github.com/kubernetes-sigs/kustomize/examples/helloWorld?ref=v1.0.6
В prod предпочитайте vendoring в свой репозиторий.
Transformers и патчи
Strategic merge patch
patches:
- path: patch-replicas.yaml
JSON 6902 patch
patches:
- target:
group: apps
version: v1
kind: Deployment
name: api
patch: |-
- op: replace
path: /spec/template/spec/containers/0/imagePullPolicy
value: IfNotPresent
commonAnnotations / labels
commonAnnotations:
owner: platform
contact: platform@example.com
labels:
- pairs:
env: prod
includeSelectors: false
images
images:
- name: ghcr.io/example/api
newName: registry.internal/shop/api
newTag: "1.4.2"
Удобно для air-gap: одно место смены registry.
namePrefix / nameSuffix / namespace
namespace: shop-prod
namePrefix: prod-
nameSuffix: -v2
components (переиспользуемые куски)
components/
observability/
kustomization.yaml
servicemonitor.yaml
# overlays/prod/kustomization.yaml
components:
- ../../components/observability
Helm vs Kustomize
| Helm | Kustomize | |
|---|---|---|
| Шаблоны | Go templates | Патчи поверх YAML |
| Пакеты | Charts / OCI | Обычно свой git |
| Секреты values | Часто | generators + SOPS |
| Сложность | Растёт с if | Растёт с числом патчей |
| kubectl | Нужен helm | Встроен -k |
Частый гибрид: Helm для сторонних чартов, Kustomize для своих сервисов; или helm template | в CI, а в git — уже rendered + kustomize (спорно). Argo CD умеет оба.
# Сравнение рендера
kubectl kustomize overlays/prod > /tmp/prod.yaml
helm template my-api ./chart -f values-prod.yaml > /tmp/helm.yaml
SOPS / sealed secrets
В overlay не храните plaintext. Паттерны:
secretGeneratorиз локального файла, который не в git (.gitignore).- SealedSecret манифест как resource.
- SOPS-encrypted файл + plugin/CI decrypt перед apply.
resources:
- sealed-api-secrets.yaml
GitOps flow
main
└─ apps/shop/{base,overlays/prod}
Argo CD Application → path: apps/shop/overlays/prod
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: shop-api
namespace: argocd
spec:
project: default
source:
repoURL: https://github.com/example/gitops.git
path: apps/shop/overlays/prod
destination:
server: https://kubernetes.default.svc
namespace: shop-prod
syncPolicy:
automated:
prune: true
selfHeal: true
Мини-практика
mkdir -p demo/{base,overlays/dev}
# положите deployment/service + kustomization как выше
kubectl kustomize demo/overlays/dev | head -50
kubectl apply -k demo/overlays/dev --dry-run=client -o yaml | head
kubectl diff -k demo/overlays/dev
kubectl kustomize demo/overlays/dev
Частые ошибки
- Патч не матчит
metadata.nameпослеnamePrefix— патчьте короткое имя из base. - Забыли добавить новый файл в
resources:. disableNameSuffixHash: true+ забыли rollout — конфиг не обновился.- Разные overlays правят один и тот же remote base без pin revision.
- Секреты в plaintext literals в git.
kubectl kustomize overlays/prod --enable-helm # если helmCharts в kustomization
Пример helmCharts (встроенная интеграция):
helmCharts:
- name: redis
repo: https://charts.bitnami.com/bitnami
version: 19.0.0
releaseName: redis
namespace: shop-prod
valuesInline:
architecture: standalone
auth:
enabled: false
Удобно, но усложняет воспроизводимость — pin версий жёстко.
Что делает команда `kubectl apply -k overlays/prod`?
Чеклист готовности
Я уверенно умею
0 / 3 выполнено
Дочитали до конца?
Отметьте урок пройденным — так проще вернуться туда, где остановились.