Python client for accessing kubernetes cluster on GKE

10/6/2019

I am struggling to programmatically access a kubernetes cluster running on Google Cloud. I have set up a service account and pointed GOOGLE_APPLICATION_CREDENTIALS to a corresponding credentials file. I managed to get the cluster and credentials as follows:

import google.auth
from google.cloud.container_v1 import ClusterManagerClient
from kubernetes import client

credentials, project = google.auth.default(
    scopes=['https://www.googleapis.com/auth/cloud-platform',])

credentials.refresh(google.auth.transport.requests.Request())

cluster_manager = ClusterManagerClient(credentials=credentials)
cluster = cluster_manager.get_cluster(project, 'us-west1-b', 'clic-cluster')

So far so good. But then I want to start using the kubernetes client:

config = client.Configuration()
config.host = f'https://{cluster.endpoint}:443'
config.verify_ssl = False
config.api_key = {"authorization": "Bearer " + credentials.token}
config.username = credentials._service_account_email

client.Configuration.set_default(config)

kub = client.CoreV1Api()
print(kub.list_pod_for_all_namespaces(watch=False))

And I get an error message like this:

pods is forbidden: User "12341234123451234567" cannot list resource "pods" in API group "" at the cluster scope: Required "container.pods.list" permission.

I found this website describing the container.pods.list, but I don't know where I should add it, or how it relates to the API scopes described here.

-- Lucas
google-kubernetes-engine
kubernetes
python

1 Answer

10/6/2019

As per the error:

pods is forbidden: User "12341234123451234567" cannot list resource "pods" in API group "" at the cluster scope: Required "container.pods.list" permission.

it seems evident the user credentials you are trying to use, does not have permission on listing the pods.

The entire list of permissions mentioned in https://cloud.google.com/kubernetes-engine/docs/how-to/iam, states the following:

There are different Role which can play into account here:

  • If you are able to get cluster, then it is covered with multiple Role sections like: Kubernetes Engine Cluster Admin, Kubernetes Engine Cluster Viewer, Kubernetes Engine Developer & Kubernetes Engine Viewer
  • Whereas, if you want to list pods kub.list_pod_for_all_namespaces(watch=False) then you might need Kubernetes Engine Viewer access.

enter image description here

You should be able to add multiple roles.

-- Nagaraj Tantri
Source: StackOverflow