如何使用 kubectl 补丁将 Serviceaccout 添加到现有 Clusterrolebinding

Pra*_*esh 1 kubernetes kustomize

这是我现有的集群角色绑定

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: example-role
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: test-role
subjects:
- kind: ServiceAccount
  name: test-sa
  namespace: ns1
Run Code Online (Sandbox Code Playgroud)

我打算在另一个命名空间(例如:ns2)中添加相同的 ServiceAccount (test-sa) 并将其与我的 ClusterRole "test-role" 绑定。

我试过的

subjects:
- kind: ServiceAccount
  name: test-sa
  namespace: ns2
Run Code Online (Sandbox Code Playgroud)

我尝试应用上面的 yaml 文件,例如

kubectl patch  clusterrolebinding <clusterrolebinding-name> --type="strategic"  --patch "$(cat role.yaml)"
Run Code Online (Sandbox Code Playgroud)

结果

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: example-role
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: test-role
subjects:
- kind: ServiceAccount
  name: test-sa
  namespace: ns2
Run Code Online (Sandbox Code Playgroud)

它在新的命名空间中添加了带有 sa 的 ClusterRoleBinding 但我在命名空间 ns1 中的现有绑定被删除了..编辑这个 cluserrolebinding,这就是我选择 kubectl 补丁的原因

har*_*riK 5

你可以试试下面的命令。有效。请参阅此处

kubectl patch clusterrolebinding example-role --type='json' -p='[{"op": "add", "path": "/subjects/1", "value": {"kind": "ServiceAccount", "name": "test-sa","namespace": "ns2" } }]'
Run Code Online (Sandbox Code Playgroud)

op - 手术 add

subjects/1 - 添加到主题数组的第一个位置

subjects:
- kind: ServiceAccount
  name: test-sa
  namespace: ns1
- kind: ServiceAccount
  name: test-sa
  namespace: ns2
Run Code Online (Sandbox Code Playgroud)