You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Kustomize向ClusterRoleBinding的subjects数组添加ServiceAccount?

问题

需要通过Kustomize向ClusterRoleBinding的subjects数组中添加两个ServiceAccount,最终期望的配置如下:

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

尝试用以下两个补丁分别添加:
第一个补丁:

- op: add
  path: "/subjects/0"
  value:
    kind: ServiceAccount
    name: name
    namespace: test1

第二个补丁:

- op: add
  path: "/subjects/1"
  value:
    kind: ServiceAccount
    name: name
    namespace: test2

但最终结果出现了重复的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: test1 # 重复项
正确的添加方式

推荐方法:使用JSON Patch的数组追加语法

使用/subjects/-作为路径,这个语法表示将元素追加到数组的末尾,不管数组当前是否已有元素,能彻底避免索引冲突导致的重复问题。

可以选择合并到一个补丁文件,或者分两个补丁文件添加:

单个补丁文件添加两个ServiceAccount

- op: add
  path: "/subjects/-"
  value:
    kind: ServiceAccount
    name: name
    namespace: test1
- op: add
  path: "/subjects/-"
  value:
    kind: ServiceAccount
    name: name
    namespace: test2

分两个补丁文件添加

第一个补丁文件(添加test1的ServiceAccount):

- op: add
  path: "/subjects/-"
  value:
    kind: ServiceAccount
    name: name
    namespace: test1

第二个补丁文件(添加test2的ServiceAccount):

- op: add
  path: "/subjects/-"
  value:
    kind: ServiceAccount
    name: name
    namespace: test2

补充:覆盖整个subjects数组(仅适合原数组为空的场景)

如果原ClusterRoleBinding的subjects数组原本是空的,也可以直接用单个补丁覆盖整个数组:

- op: add
  path: "/subjects"
  value:
    - kind: ServiceAccount
      name: name
      namespace: test1
    - kind: ServiceAccount
      name: name
      namespace: test2

注意:这种方式会替换整个subjects数组,如果原数组已有其他元素,会被全部覆盖,因此仅适合初始为空的情况。


内容的提问来源于stack exchange,提问作者Murakami

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 19:56:09