首页 > 解决方案 > Amazon EKS:通过 python 脚本生成/更新 kubeconfig

问题描述

在使用 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 文档时,我似乎无法找到上述aws例程的等效项。也许我看错地方了。

标签: kubernetesboto3aws-cliamazon-eks

解决方案


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

# 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)

推荐阅读