在多环境部署中,经常碰到不同的环境下只有deployment中的Image Tag不一样,其他是一样的。这样我们只需要在kustomization.yaml文件中配置重用另外一个环境的配置所有文件并覆盖 image Tag,就可以达到效果,这样可以精简配置文件数量。
例如,测试环境和生产环境只有image的标签不一样:
- 测试环境标签:hello-1.0.0-rc1
- 生产环境标签:hello-1.0.0
文件组织结构如下:
hello
├── base
│ ├── deployment.yaml
│ ├── kustomization.yaml
│ └── service.yaml
├── production
│ ├── hello1
│ │ ├── envs.yaml
│ │ ├── kustomization.yaml
│ ├── hello2
│ │ ├── envs.yaml
│ │ ├── kustomization.yaml
│ └── kustomization.yaml
└── staging
└── kustomization.yaml
其中:
- hello/base: 基础文件,staging和production利用base文件夹下的文件为公共模版。
- hello/staging: 发布到测试环境的配置文件。
- hello/production: 发布到生产环境的配置文件。
production/hello1/kustomizetion.yaml文件配置内容如下(重用hello/base的文件):
$ cat production/hello1/kustomization.yaml
namePrefix: hello1-
commonLabels:
release: hello1
bases:
- ../../base/
patches:
- envs.yaml
production/kustomization.yaml 文件配置如下:
bases:
- ./hello1
- ./hello2
images:
- name: reg.hello.com/hello
newTag: 1.0.0
在 staging/kustomization.yaml中配置引用production的配置文件,并覆盖image 的Tag,配置如下:
bases:
- ../production
images:
- name: reg.hello.com/hello
newTag: 1.0.0-RC1
生成的k8s描述文件,只有image的Tag,不一样。(通常RC版发布到测试环境)。
$ kustomize build staging
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: hello
release: hello1
name: hello1-hello
spec:
replicas: 1
selector:
matchLabels:
app: hello
release: hello
template:
metadata:
labels:
app: hello
release: hello1
spec:
containers:
image: reg.hello.com/hello:1.0.0-RC1
......
$ kustomize build production
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: hello
release: hello1
name: hello1-hello
spec:
replicas: 1
selector:
matchLabels:
app: hello
release: hello
template:
metadata:
labels:
app: hello
release: hello1
spec:
containers:
image: reg.hello.com/hello:1.0.0
......
注:kustomizeation的image字段,是根据name查找父配置的image,并覆盖。这里是:reg.hello.com/hello
当然,你也可以在staging/kustomization.yaml 中定义更多字段,如:commonLabels、namePrefix...覆盖或增加更多选项。
更多kustomization字段说明:https://github.com/kubernetes-sigs/kustomize/blob/master/docs/fields.md#transformers