AWS EKS - 从 Pod 内部验证 Kubernetes python lib



>Objective

我想从正在运行的 Pod 内部连接并调用 Kubernetes REST API,有问题的 Kubernetes 是使用 IAM 身份验证的 AWS EKS 集群。所有这些都使用 Kubernetes Python lib。

我试过什么

从我的python file内部:

from kubernetes import client, config
config.load_incluster_config()
v1 = client.CoreV1Api()
ret = v1.list_pod_for_all_namespaces(watch=False)

上面的命令抛出了一个403错误,我相信这是由于 AWS EKS 使用的不同身份验证机制。

我已经知道的奏效

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)

虽然上述方法有效,但我必须对通过 kubectl 在本地生成的令牌进行硬编码,并将其签入存在安全风险的代码中。

有没有更合适的方法来使用 AWS EKS 验证 Kubernetes python 库?

可以使用以下方法获取令牌。这假定您已在容器/服务器/笔记本电脑上成功安装并配置 aws-iam 身份验证器。

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("<cluster_name>")
configuration = client.Configuration()
configuration.host = '<api_endpoint>'
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

有一个 kubernetes-client/python-base 的 PR 增加了对 exec 插件的支持,尝试在 kubeconfig 中实现 exec-plugins 支持。