1
votes

This is my existing clusterrolebinding

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

i am planning to add the same ServiceAccount (test-sa) in another namespace (for eg:ns2) and bind it with my ClusterRole "test-role" .

what i have tried

subjects:
- kind: ServiceAccount
  name: test-sa
  namespace: ns2

i tried to apply the yaml file above like

kubectl patch  clusterrolebinding <clusterrolebinding-name> --type="strategic"  --patch "$(cat role.yaml)"

Result

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

It is adding the ClusterRoleBinding with sa in new namespace but my existing binding in namespace ns1 got removed .. is there any way to merge the new changes instead of replace ..iam trying do it in an automated way ..like a bash script for editing this cluserrolebinding,thats why i choose kubectl patch

1

1 Answers

5
votes

You can try below command. It worked. Refer here.

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

op - operation add

subjects/1 - add to subjects array's first position

subjects:
- kind: ServiceAccount
  name: test-sa
  namespace: ns1
- kind: ServiceAccount
  name: test-sa
  namespace: ns2