Kustomize 是一款无需模板即可自定义 Kubernetes YAML 文件的工具。它允许你以声明的方式创建可修改 Kubernetes 基本配置的覆盖。
下面是一个使用 Kustomize 定制 Kubernetes 部署的示例。
【代码清单】
# Create a directory for your base YAML
mkdir -p my-app/base
# Create a simple deployment YAML file in the base directory
cat <<EOF > my-app/base/deployment.apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 2
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-app
image: nginx:1.17.10
EOF
# Create a Kustomization file in the same base directory
cat <<EOF > my-app/base/kustomization.resources:
- deployment.EOF
# Now create an overlay to change the number of replicas
mkdir -p my-app/overlay
# Create a kustomization file in the overlay directory
cat <<EOF > my-app/overlay/kustomization.resources:
- ../base
patchesStrategicMerge:
- deployment-patch.EOF
# Create the patch file to increase replicas
cat <<EOF > my-app/overlay/deployment-patch.apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 5
EOF
# Build the customized deployment using Kustomize
kustomize build my-app/overlay
【执行结果】
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 5
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-app
image: nginx:1.17.10
Kustomize 允许你将 Kubernetes 的基本配置与特定环境的自定义配置分开维护。通过使用覆盖,您可以将不同的自定义应用到基础配置,而无需重复 YAML 文件。这种方法能让你的 Kubernetes 配置保持 DRY(不重复),并让你更容易管理不同的环境,如开发、暂存和生产环境。Kustomize 原生集成在 kubectl 中,这意味着你无需安装任何其他工具就能使用它。当运行 kubectl apply -k ./overlay 时,它会自动应用 Kustomize 设置中定义的定制资源。Kustomize 使用一种名为 “patchesStrategicMerge ”的概念,以声明的方式修改现有字段,确保你的定制可以轻松应用和管理。
【小知识】
Kustomize 是第一款 Kubernetes 原生配置工具,允许在不使用模板的情况下采用更声明式的管理风格。它在 1.14 版本中被集成到 kubectl 中,使 Kubernetes 用户可以开箱即用。