403 Forbidden error when trying to access Kubernetes API from a pod

anushiya-thevapalan picture anushiya-thevapalan · Oct 21, 2019 · Viewed 10.2k times · Source

As per this Documentation, I am trying to access the Kuberenetes API from a pod, using the following command

curl --cacert ca.crt -H "Authorization: Bearer $(<token)" https://kubernetes/apis/extensions/v1beta1/namespaces/default/deployments/ballerina-prime/scale

which follows the following template

curl --cacert ca.crt -H "Authorization: Bearer $(<token)" https://kubernetes/apis/extensions/v1beta1/namespaces/{namespace}/deployments/{name}/scale

It throws the following error

{
  "kind": "Status",
  "apiVersion": "v1",
  "metadata": {

  },
  "status": "Failure",
  "message": "deployments.extensions \"ballerina-prime\" is forbidden: User \"system:serviceaccount:default:default\" cannot get resource \"deployments/scale\" in API group \"extensions\" in the namespace \"default\"",
  "reason": "Forbidden",
  "details": {
    "name": "ballerina-prime",
    "group": "extensions",
    "kind": "deployments"
  },
  "code": 403
}

Can someone point out where I am making mistake or suggest any other way in which I can access the Kubernetes API?

Update 01

I created a Role as per the Documentation suggested. Following is the manifest I used.

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: default
  name: deployments-and-deployements-scale
rules:
- apiGroups: [""]
  resources: ["deployments", "deployments/scale"]
  verbs: ["get", "list"]

I applied it using this command. kubectl apply -f deployments-and-deployements-scale.yaml. Still I am unable to access the endpoint needed. Where am I making mistake?

Answer

Thomas picture Thomas · Oct 21, 2019

First, you are connecting correctly to the kubernetes API!

But the default serviceaccount ("user") you are using does not have the required privileges to perform the operation, that you want to do. (Reading the deployment 'ballerina-prima' in the namespace 'default')

What you need to do: Use a different serviceaccount or grant the permissions that are required to the default service account.

You can find detailed information in the documentation: https://kubernetes.io/docs/reference/access-authn-authz/rbac/