Authenticate with Kubernetes cluster with token

10/4/2018

The way my environment is setup (AWS EKS) is that in my ~/.kube/config the user has an exec configuration to make a call to aws-iam-authenticator.

This is so that when kubectl is run, it'll request the token to auth to the Kubernetes cluster.

I'm currently writing a client application that will interact with the Kubernetes API. This is written in Python, using the official Python client.

When doing any of the examples, I get the error that system:anonymous isn't allowed to perform a certain operation (e.g. list pods). I think the root of the problem is that I need to pass a token from aws-iam-authenticator to my client requests.

Unfortunately I can't seem to figure out how to pass this token in with the Python client for Kubernetes. I see this snippet but I get an error that api_key attribute isn't part of the configuration module (and sure enough, it isn't).

How am I supposed to inject the token into my requests from the Python client for Kubernetes?

Thanks in advance!

-- Thomas Stringer
kubernetes
python

1 Answer

10/4/2018

I believe you need the 'Authorization: Bearer ' header configured through this: configuration.api_key_prefix['authorization'] = 'Bearer'. So basically:

from __future__ import print_function
import time
import kubernetes.client
from kubernetes.client.rest import ApiException
from pprint import pprint

# Configure API key authorization: BearerToken
configuration = kubernetes.client.Configuration()
configuration.api_key['authorization'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
configuration.api_key_prefix['authorization'] = 'Bearer' ## <== This one

# create an instance of the API class
api_instance = kubernetes.client.ApiregistrationV1Api(kubernetes.client.ApiClient(configuration))
body = kubernetes.client.V1APIService() # V1APIService | 
pretty = 'pretty_example' # str | If 'true', then the output is pretty printed. (optional)

try: 
    api_response = api_instance.create_api_service(body, pretty=pretty)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling ApiregistrationV1Api->create_api_service: %s\n" % e)

It's basically described here

-- Rico
Source: StackOverflow