更新至 Kustomize 3.2.1 版本
Kustomize 是 Kubernetes 原生配置管理工具。在 Kubernetes 1.14 版本之后,内置于 kubectl。
如果将 Kustomize 和面向对象编程作比较,Base 类似于基类,Overlay 类似于子类。在 Kustomize,Base 实现共同功能,Overlay 继承 Base 并实现定制功能。
可以通过 overlay 实现不同项目阶段环境,开发环境、测试环境、预发环境和线上环境。
安装
macOS 可以使用包管理工具 Brew 安装:
brew install kustomize
目录
以 Spring Boot 应用举🌰,对应测试环境 test 和线上环境 prod。
目录结构如下所示:
├── base
│ ├── deployment.yaml
│ ├── kustomization.yaml
│ └── service.yaml
└── overlays
├── prod
│ ├── deployment.yaml
│ └── kustomization.yaml
└── test
├── deployment.yaml
└── kustomization.yaml
Kustomization 由一个 kustomization.yaml 配置文件和零到多个资源文件组成。
kustomization.yaml 配置文件可以手动创建,也可以通过 kustomize 命令行工具创建。
创建 base/kustomization.yaml 配置文件举🌰:
kutomize create --resources deployment.yaml,service.yaml
创建 overlays/test/kustomization.yaml 配置文件举🌰:
kutomize create --resources deployment.yaml,../../base
Kustomization
Kustomization 包含了以下四类字段:
- meta 元数据
- resource 声明资源
- transformer 转换资源
- generator 生成资源
Base
base/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: spring-app-deploy
spec:
replicas: 1
selector:
matchLabels:
app: spring-app
template:
metadata:
labels:
app: spring-app
spec:
containers:
- name: spring-app
image: spring-app:0.1
ports:
- name: web
containerPort: 8080
base/service.yaml
apiVersion: v1
kind: Service
metadata:
name: spring-app-svc
spec:
selector:
app: spring-app
ports:
- name: web
port: 8080
targetPort: web
base/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- service.yaml
- deployment.yaml
① resources 添加资源配置项 service.yaml 和 deployment.yaml。
Overlay
overlays/test/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: spring-app-deploy
spec:
template:
spec:
containers:
- name: spring-app
volumeMounts:
- mountPath: /app/conf
name: spring-app-conf
resources:
limits:
memory: "1Gi"
cpu: "200m"
volumes:
- name: spring-app-conf
configMap:
name: spring-app-cm
items:
- key: application.properties
path: application.properties
overlays/test/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
bases:
- ../../base
commonAnnotations:
env: test
patchesStrategicMerge:
- deployment.yaml
configMapGenerator:
- name: spring-app-cm
files:
- application.properties
① bases 声明 Base;
② patchesStrategicMerge 合并资源配置;
③ configMapGenerator 生成 ConfigMap 资源。
使用
打印生成的资源:
kubectl kustomize <目录>
创建资源:
kubectl apply -k <目录>
查看资源:
kubectl get -k <目录>
删除资源:
kubectl delete -k <目录>
参考
- Kustomize - Kubernetes native configuration management
- kubernetes-sigs/kustomize: Customization of kubernetes YAML configurations
- Kustomization.yaml Reference - The Kubelet Book
- Declarative Management of Kubernetes Objects Using Kustomize - Kubernetes
- Introduction to Kustomize, Part 1: Creating a Kubernetes app out of multiple pieces - Mirantis Blog
- Introduction to Kustomize, Part 2: Overriding values with overlays - Mirantis Blog