How to deal with a namespace different from the globally set one?

3/5/2021
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

Let's assume above situation. The problem is objects specified in r2.yaml would be place in ns1 even if ns2 is explicitely referenced in metadata.namespace.

How do I have to deal with this? Or how can I solve this (as I assume there a multiple options)?

-- Raffael
kubernetes
kustomize

1 Answer

3/16/2021

I've looked into this and I came up with one idea.

├── 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

You need to have 2 directories, in this setup are: base and prod. In base directory you should use your base YAMLs and kustomization.yaml file. In my scenario I have 6 YAMLs: nginx/1/2/3/4.yaml based on Kubernetes Documentation, and nginx5.yaml which looks the same but with additional spec.namespace: nginx.

In base directory:

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

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

And 5 YAMLs with nginx.

In Prod directory:

You should have 2 files. kustomization.yaml and patch.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

When you will use kustomize build . in prod directory, all nginx-deployment/-2/-3/-4 will be in the namespace: ns1 and nginx-deployment-5 will be in 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:

Useful links:

-- PjoterS
Source: StackOverflow