<h2>Objective</h2>

<p>I want to connect to and call Kubernetes REST APIs from inside a running pod, the Kubernetes in question is an AWS EKS cluster using IAM authentication. All of this using Kubernetes Python lib.</p>

<h2>What I have tried</h2>

<p>From inside my <code>python file</code>:</p>

<pre><code>from kubernetes import client, config

config.load_incluster_config()
v1 = client.CoreV1Api()
ret = v1.list_pod_for_all_namespaces(watch=False)
</code></pre>

<p>The above command throws a <code>403</code> error, This I believe is due to the different auth mechanism that AWS EKS uses.</p>

<h2>What I already know works</h2>

<pre><code>ApiToken = 'eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9.xxx.yyy'
    configuration = client.Configuration()
    configuration.host = 'https://abc.sk1.us-east-1.eks.amazonaws.com'
    configuration.verify_ssl = False
    configuration.debug = True
    configuration.api_key = {"authorization": "Bearer " + ApiToken}
    client.Configuration.set_default(configuration)
</code></pre>

<p>While the above works, I have to hardcode a token that I generate locally via kubectl and check it into the code which is a security risk.</p>

<p>Is there a more proper way to authenticate the Kubernetes python lib with AWS EKS?</p>

<p>You can use the following method to get the token. This assumes that you have successfully installed and configured <a href="https://docs.aws.amazon.com/eks/latest/userguide/install-aws-iam-authenticator.html" rel="nofollow noreferrer">aws-iam-authenticator</a> on your pod/server/laptop.</p>

<pre><code>def get_token(cluster_name):
    args = ("/usr/local/bin/aws-iam-authenticator", "token", "-i", cluster_name, "--token-only")
    popen = subprocess.Popen(args, stdout=subprocess.PIPE)
    popen.wait()
    return popen.stdout.read().rstrip()

api_token = get_token("&lt;cluster_name&gt;")
configuration = client.Configuration()
configuration.host = '&lt;api_endpoint&gt;'
configuration.verify_ssl = False
configuration.debug = True
configuration.api_key['authorization'] = "Bearer " + api_token
configuration.assert_hostname = True
configuration.verify_ssl = False
client.Configuration.set_default(configuration)

v1 = client.CoreV1Api()
ret = v1.list_pod_for_all_namespaces(watch=False)
print ret
</code></pre>

<p>There is an PR for kubernetes-client/python-base that adds support for exec plugins, <a href="https://github.com/kubernetes-client/python-base/pull/75" rel="nofollow noreferrer">Attempt to implement exec-plugins support in kubeconfig</a>.  </p>
