kuberneteskubernetes-go-client

"Forbidden" error when trying to delete kubernetes pods


I'm trying to delete kubernetes pod via go-client library using the following code:

err := ks.clientset.CoreV1().Pods(kubeData.PodNamespace).Delete(context.Background(), kubeData.PodName, metav1.DeleteOptions{})
if err != nil {
  log.Fatal(err)
}

However receiving an error:

pods "app-name" is forbidden: User "system:serviceaccount:default:app-name" cannot delete resource "pods" in API group "" in the namespace "default""

Here is the serviceaccount.yaml:

{{- $sa := print .Release.Name "-" .Values.serviceAccount -}}
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ $sa }}
  namespace: {{ .Release.Namespace }}

---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: {{ $sa }}
rules:
  - apiGroups: ["apps"]
    verbs: ["patch", "get", "list"]
    resources:
      - deployments
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: {{ $sa }}
rules:
  - apiGroups: ["apps"]
    verbs: ["delete", "get", "list"]
    resources:
      - pods
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: {{ $sa }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: {{ $sa }}
subjects:
  - kind: ServiceAccount
    name: {{ $sa }}

Looks like something related to user permissions, however not sure how to properly configure it. Thanks.


Solution

  • As you can see from the error:

    pods "app-name" is forbidden: User "system:serviceaccount:default:app-name" cannot delete resource "pods" in API group "" in the namespace "default""

    The important part is: in API group ""

    Take a look on your manifest:

    apiVersion: rbac.authorization.k8s.io/v1
    kind: Role
    metadata:
      name: {{ $sa }}
    rules:
      # - apiGroups: ["apps"] # <-- BAD!
      - apiGroups: [""] # <-- GOOD!
        verbs: ["delete", "get", "list"]
        resources:
          - pods
    

    This definition is specifying that a resource Pod is in the apiGroup: apps which is not correct and "" should be used instead.

    More on that you can read here: