Amazon EKS:通过python脚本生成/更新kubeconfig

时间:2019-03-01 22:30:14

标签: kubernetes boto3 aws-cli amazon-eks

使用Amazon的K8s产品 EKS 服务时,有时需要将Kubernetes API和配置连接到AWS内建立的基础架构。特别是,我们需要具有适当凭据和URL的 kubeconfig 才能连接到EKS提供的k8s控制平面。

Amazon命令行工具aws提供了执行此任务的例程

aws eks update-kubeconfig --kubeconfig /path/to/kubecfg.yaml --name <EKS-cluster-name>

问题:通过Python / boto3做同样的事情

查看Boto API documentation时,似乎无法发现上述aws例程的等效内容。也许我在找错地方了。

  • boto 中是否有现成的函数来实现这一目标?
  • 否则,您将如何在python中直接处理此问题(除了在子进程中调出aws以外)?

3 个答案:

答案 0 :(得分:2)

没有方法函数可以执行此操作,但是您可以像下面这样自己构建配置文件:

# Set up the client
s = boto3.Session(region_name=region)
eks = s.client("eks")

# get cluster details
cluster = eks.describe_cluster(name=cluster_name)
cluster_cert = cluster["cluster"]["certificateAuthority"]["data"]
cluster_ep = cluster["cluster"]["endpoint"]

# build the cluster config hash
cluster_config = {
        "apiVersion": "v1",
        "kind": "Config",
        "clusters": [
            {
                "cluster": {
                    "server": str(cluster_ep),
                    "certificate-authority-data": str(cluster_cert)
                },
                "name": "kubernetes"
            }
        ],
        "contexts": [
            {
                "context": {
                    "cluster": "kubernetes",
                    "user": "aws"
                },
                "name": "aws"
            }
        ],
        "current-context": "aws",
        "preferences": {},
        "users": [
            {
                "name": "aws",
                "user": {
                    "exec": {
                        "apiVersion": "client.authentication.k8s.io/v1alpha1",
                        "command": "heptio-authenticator-aws",
                        "args": [
                            "token", "-i", cluster_name
                        ]
                    }
                }
            }
        ]
    }

# Write in YAML.
config_text=yaml.dump(cluster_config, default_flow_style=False)
open(config_file, "w").write(config_text)

答案 1 :(得分:0)

https://docs.aws.amazon.com/eks/latest/userguide/create-kubeconfig.html手动创建kubeconfig 部分对此进行了说明,实际上是从boto3 EKS文档中引用的。那里的手动方法与@jaxxstorm的答案非常相似,不同的是它没有显示您需要的python代码,但是也没有假定heptio antenticator(它显示了令牌和IAM身份验证器方法)。

答案 2 :(得分:0)

我遇到了决定将其实现为Python包的相同问题 可以通过

安装
pip install eks-token

然后简单地做

from eks_token import get_token
response = get_token(cluster_name='<value>')

更多详细信息和示例here