brandizzi
brandizzi

Reputation: 27050

Error "cannot unmarshal array into Go struct field ClusterRoleBinding.roleRef of type v1.RoleRef" when crewating ClusterRoleBinding in Kubernetes

I'm trying to create a ClusterRoleBinding for an exercise in a course with the YAML file below:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: nodes-admin
rules:
  - apiGroups: [""]
    resources:
      - nodes
    verbs:
      - get
      - list
      - create
      - delete
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: nodes-admin
subjects:
  - apiGroup: rbac.authorization.k8s.io
    kind: User
    name: user1387
roleRef:
  - apiGroup: rbac.authorization.k8s.io
    kind: ClusterRole
    name: nodes-admin

Yet it keeps failing with:

Error from server (BadRequest): error when creating "clusterrole.yaml": ClusterRoleBinding in version "v1" cannot be handled as a ClusterRoleBinding: json: cannot unmarshal array into Go struct field ClusterRoleBinding.roleRef of type v1.RoleRef

I investigate for some time but couldn't really understand what is going on. What's the error?

Upvotes: 1

Views: 975

Answers (1)

brandizzi
brandizzi

Reputation: 27050

The problem is that the roleRef field expects one object with fields apiGroup, kind and name. When you put the - before the apiGroup under roleRef, you are creating an array of objects (containing, sure, only one object, but nonetheless passing the wrong type of value to roleRef). The solution is to remove that -:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: nodes-admin
subjects:
  - apiGroup: rbac.authorization.k8s.io
    kind: User
    name: user1387
roleRef:
  apiGroup: rbac.authorization.k8s.io  # ⇦ Changed here
  kind: ClusterRole                    # compare with the
  name: nodes-admin                    # original

The error message does actually explain that, even if it may be a bit hard to understand sometimes:

cannot unmarshal array into Go struct field ClusterRoleBinding.roleRef of type v1.RoleRef

Upvotes: 0

Related Questions