-->

Saturday, March 25, 2023

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

Issue:

When trying to delete a Kubernetes pod via the Go-client library, an error is encountered: "pods "app-name" is forbidden: User "system:serviceaccount:default:app-name" cannot delete resource "pods" in API group "" in the namespace "default""


Code:

The following code is used to delete the pod via the Go-client library:

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

The serviceaccount file that i was passing was

 {{- $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 }}  


Resolution:

The error message indicates that the user attempting to delete the pod does not have the necessary permissions. To resolve the issue, we need to check the user permissions and modify them if necessary.

In the provided serviceaccount.yaml file, we can see that the Role definition for the "app-name" service account specifies the API group as "apps":

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

However, the error message indicates that the API group should be empty: "pods "app-name" is forbidden: User "system:serviceaccount:default:app-name" cannot delete resource "pods" in API group "" in the namespace "default""

To fix the issue, we need to modify the Role definition to use an empty API group:

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

Once the Role definition has been modified, the "app-name" service account will have the necessary permissions to delete pods, and the error should no longer occur. 

0 comments:

Post a Comment