使用 kubectl kustomize 将项目添加到列表

Adding items to a list with kubectl kustomize

我想将 base/foo.yaml 应用到我的所有环境中,部分看起来像这样

Kubernetes:
  deploymentPatches:
    - patch: |-
      - {"op": "add", "path": "/spec/template/spec/volumes/-", "value": {"name": "volume", "secret": {"secretName": "my-secret"}}}
      - {"op": "add", "path": "/spec/template/spec/containers/0/volumeMounts/-", "value": {"mountPath": "/connections", "name": "volume"}}

现在我也想添加特定于环境的补丁,所以我在 运行 之后的最终目标是kubectl kustomize accept 应该是

Kubernetes:
  deploymentPatches:
    - patch: |-
      - {"op": "add", "path": "/spec/template/spec/volumes/-", "value": {"name": "volume", "secret": {"secretName": "my-secret"}}}
      - {"op": "add", "path": "/spec/template/spec/containers/0/volumeMounts/-", "value": {"mountPath": "/connections", "name": "volume"}}
      - {"op": "add", "path": "/spec/template/spec/containers/0/env/-", "value": {"name": "MY_ENVIRONMENT", "value": "accept"}}

Kubernetes:
  deploymentPatches:
    - patch: |-
      - {"op": "add", "path": "/spec/template/spec/volumes/-", "value": {"name": "volume", "secret": {"secretName": "my-secret"}}}
      - {"op": "add", "path": "/spec/template/spec/containers/0/volumeMounts/-", "value": {"mountPath": "/connections", "name": "volume"}}
  - patch: |-
      - {"op": "add", "path": "/spec/template/spec/containers/0/env/-", "value": {"name": "MY_ENVIRONMENT", "value": "accept"}}

我将如何设置我的 kustomize 配置来完成此操作?到目前为止,我已经尝试了以下方法:

kustomize.yaml

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
bases:
  - ../base
patchesStrategicMerge:
  - foo.yaml

accept/foo.yaml

Kubernetes:
  deploymentPatches:
    - patch: |-
      - {"op": "add", "path": "/spec/template/spec/containers/0/env/-", "value": {"name": "MY_ENVIRONMENT", "value": "accept"}}

我遇到的问题在 strategic merge patch docs;

中有解释

In the standard JSON merge patch, JSON objects are always merged but lists are always replaced. Often that isn't what we want.

To solve this problem, Strategic Merge Patch uses the go struct tag of the API objects to determine what lists should be merged and which ones should not.

这就是使用 patchesStrategicMerge.

添加额外容器(如果您对要附加的容器使用不同的名称)的原因

但是,我试图将项目附加到的对象和列表不是这样设置的,因此只是被替换了。

由于我无法更改设置,我的解决方案是求助于 patchesJson6902

patch.yaml

- op: add
  path: /spec/Kubernetes/deploymentPatches/-
  value:
    patch: |-
      - op: add
        path: /spec/template/spec/containers/0/env/-
        value:
          name: MY_ENVIRONMENT
          value: accept

kustomization.yaml

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
bases:
  - ../base
patchesJson6902:
- target:
    group: mygroup
    version: v1
    kind: myobject
    name: myname
  path: patch.yaml