如何处理不同于全局设置的命名空间?

时间:2021-03-05 11:22:39

标签: kubernetes kustomize

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

namespace: ns1

resources:
  - r1a.yaml
  - r1b.yaml
  - r1c.yaml
  - r1d.yaml
  - r1e.yaml
  - r2.yaml # needs to be placed in namespace ns2

让我们假设上述情况。问题是 r2.yaml 中指定的对象将放置在 ns1 中,即使 ns2metadata.namespace 中被显式引用。

我该如何处理?或者我该如何解决这个问题(因为我假设有多种选择)?

1 个答案:

答案 0 :(得分:1)

我已经研究过这个问题,并提出了一个想法。

├── base
│   ├── [nginx.yaml]  Deployment nginx ns: default
|   ├── [nginx2.yaml]  Deployment nginx ns: default
|   ├── [nginx3.yaml]  Deployment nginx ns: default
|   ├── [nginx4.yaml]  Deployment nginx ns: default
|   ├── [nginx5.yaml]  Deployment nginx ns: nginx
│   └── [kustomization.yaml]  Kustomization 
└── prod
    ├── [kustomization.yaml]  Kustomization 
    └── [patch.yaml] patching namespace

您需要有 2 个目录,在此设置中是:baseprod。在 base 目录中,您应该使用基本 YAML 和 kustomization.yaml 文件。在我的场景中,我有 6 个 YAML:基于 Kubernetes Documentationnginx/1/2/3/4.yamlnginx5.yaml,它看起来相同但有额外的 spec.namespace: nginx

base 目录中:

$ cat kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

resources:
- nginx1.yaml
- nginx2.yaml
- nginx3.yaml
- nginx4.yaml
- nginx5.yaml

和 5 个带有 nginx 的 YAML。

Prod 目录中:

您应该有 2 个文件。 kustomization.yamlpatch.yaml

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: ns1
bases:
- ../base
patchesJson6902:
- target:
    group: apps
    version: v1
    kind: Deployment
    name: nginx-deployment-5
  path: patch.yaml

$ cat patch.yaml
- op: replace
  path: /metadata/namespace
  value: nginx

当您在 kustomize build . 目录中使用 prod 时,所有 nginx-deployment/-2/-3/-4 都将在 namespace: ns1 中,而 nginx-deployment-5 将在 namespace: nginx 中。

~/prod (project)$ kustomize build .
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment-5
  namespace: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - image: nginx:1.14.2
        name: nginx
        ports:
        - containerPort: 80
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  namespace: ns1
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - image: nginx:1.14.2
        name: nginx
        ports:
        - containerPort: 80
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment-2
  namespace: ns1
spec:

有用的链接