Patch service account to rolebinding in k8s dosen't work correctly

10/6/2020

I was trying to patch service account to rolebinding but when i ran command for patch, it replaced whole subject field in rolebinding yml. here i show my existing config and command that i executed for expected output

command to patch :

kubectl patch rolebinding test-team-binding  --patch "$(cat patch-file.yml)" 

patch-file.yml:

subjects:
- kind: ServiceAccount
  name: user3
  namespace: test-namespace

rolebinding.yml:

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  creationTimestamp: "2020-09-08T11:24:54Z"
  managedFields:
  - apiVersion: rbac.authorization.k8s.io/v1
    fieldsType: FieldsV1
    fieldsV1:
      f:metadata:
        f:annotations:
          .: {}
          f:kubectl.kubernetes.io/last-applied-configuration: {}
      f:roleRef:
        f:apiGroup: {}
        f:kind: {}
        f:name: {}
      f:subjects: {}
    manager: kubectl
    operation: Update
    time: "2020-10-06T07:37:58Z"
  name: test-team-binding
  namespace: test-namespace
  resourceVersion: "45697451"
  selfLink: /apis/rbac.authorization.k8s.io/v1/namespaces/test-namespace/rolebindings/test-team-binding
  uid: b602b333-4ee8-4601-8c75-f3707bb19d68
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: test-team
subjects:
- kind: ServiceAccount
  name: user1
  namespace: test-namespace
- kind: ServiceAccount
  name: user2
  namespace: test-namespace

expected output:

subjects:
- kind: ServiceAccount
  name: user1
  namespace: test-namespace
- kind: ServiceAccount
  name: user2
  namespace: test-namespace
- kind: ServiceAccount
  name: user3
  namespace: test-namespace

result output:

subjects:
- kind: ServiceAccount
  name: user3
  namespace: test-namespace
-- Mohammad Falahi
kubernetes
patch
service-accounts

1 Answer

10/6/2020

You can add/replace/remove by specifying the operation in the patch command in json type, by default patch command will replace the value. The below command should work for your requirement.

kubectl patch rolebinding test-team-binding --type=json -p='[{"op": "add", "path": "/subjects/3", "value": {"kind": "ServiceAccount","name":"user3","namespace":"test-namespace" } }]'

Thanks, Kiruba

-- Kiruba
Source: StackOverflow