通过 Kustomize 将对象添加到 yaml 中的数组

Mur*_*ami 3 kubernetes kubectl kustomize

如何通过 Kustomize 将对象添加到数组?因此,我想添加两个ServiceAccounts subjects,如下所示:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: binding
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:auth-delegator
subjects:
  - kind: ServiceAccount
    name: name
    namespace: test1
  - kind: ServiceAccount
    name: name
    namespace: test2
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用该补丁:

- op: add
  path: "/subjects/0"
  value:
    kind: ServiceAccount
    name: name
    namespace: test1
Run Code Online (Sandbox Code Playgroud)

还有第二个环境的另一个补丁:

- op: add
  path: "/subjects/1"
  value:
    kind: ServiceAccount
    name: name
    namespace: test2
Run Code Online (Sandbox Code Playgroud)

但结果我得到了重复subjects,所以当然这是错误的:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: binding
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:auth-delegator
subjects:
  - kind: ServiceAccount
    name: name
    namespace: test1 // the same...
  - kind: ServiceAccount
    name: name
    namespace: test1 // ...as here
Run Code Online (Sandbox Code Playgroud)

添加它的正确方法是什么?

lar*_*sks 6

如果我从如下所示的 ClusterRoleBinding 开始crb.yaml

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: binding
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:auth-delegator
subjects: []
Run Code Online (Sandbox Code Playgroud)

我创建一个kustomization.yaml这样的文件:

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

resources:
  - crb.yaml

patches:
  - target:
      kind: ClusterRoleBinding
      name: binding
    patch: |
      - op: add
        path: /subjects/0
        value:
          kind: ServiceAccount
          name: name
          namespace: test1

  - target:
      kind: ClusterRoleBinding
      name: binding
    patch: |
      - op: add
        path: /subjects/1
        value:
          kind: ServiceAccount
          name: name
          namespace: test2
Run Code Online (Sandbox Code Playgroud)

然后我得到输出:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: binding
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:auth-delegator
subjects:
- kind: ServiceAccount
  name: name
  namespace: test1
- kind: ServiceAccount
  name: name
  namespace: test2
Run Code Online (Sandbox Code Playgroud)

我想这就是你正在寻找的东西。这有帮助吗?请注意,不要在 中显式设置索引path,例如:

path: /subjects/0
Run Code Online (Sandbox Code Playgroud)

我们可以改为指定:

path: /subjects/-
Run Code Online (Sandbox Code Playgroud)

这意味着“附加到列表”,在这种情况下将生成相同的输出。