Why am I getting "401 unauthorized" sometimes in gcloud API on GKE?

1.4k Views Asked by At

I have a google kubernetes cluster running and I am trying to manually scale some pods with the python-client kubernetes SDK. I use the following command on my terminal to get my google account credentials:

gcloud auth login

Next, I connect to my cluster using the default command to get locally my kube-config:

gcloud container clusters get-credentials ${clusterName} --zone ${zoneName}--${projectName}

Using the python SDK I load my configuration:

from kubernetes import client, config
import kubernetes.client

config.load_kube_config()
v1 = client.CoreV1Api()
api = client.CustomObjectsApi()
k8s_apps_v1 = client.AppsV1Api()

With this code I have my cluster info and I can scale my pods as needed. This works for around 30-45 mins and after that when I try to make API requests to scale the pods in my cluster I get a response with the following error:

kubernetes.client.exceptions.ApiException: (401)
Reason: Unauthorized
HTTP response headers: HTTPHeaderDict({'Audit-Id': '697f82b7-4db9-46c3-b873-cef49a45bb19', 'Cache-Control': 'no-cache, private', 'Content-Type': 'application/json', 'Date': 'Tue, 31 May 2022 01:20:53 GMT', 'Content-Length': '129'})
HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Unauthorized","reason":"Unauthorized","code":401}

Why do I get anauthorized and can't make API calls anymore, and how can I fix this ?

1

There are 1 best solutions below

0
On BEST ANSWER

To resolve it, you should refresh the token before calling the API. This doc is useful to check if the token expired, the function load_gcp_token refreshes the GCP token only if it expires.