[Script] EKS Kubeconfig Generator

This little script will generate a kubeconfig based on all EKS clusters that are currently available via aws eks list-clusters.

python3 script.py > ~/.kube/config

import boto3, yaml, os

eks = boto3.client('eks')

def build_base():
  obj = {}
  obj['apiVersion'] = 'v1'
  obj['kind'] = 'Config'
  obj['clusters'] = []
  obj['contexts'] = []
  obj['users'] = []
  obj['preferences'] = {}
  return obj

def build_cluster(cluster):
  obj = {}
  obj['cluster'] = {}
  obj['cluster']['certificate-authority-data'] = cluster['certificateAuthority']['data']
  obj['cluster']['server'] = cluster['endpoint']
  obj['name'] = cluster['name']
  return obj

def build_context(cluster):
  obj = {}
  obj['name'] = cluster['name']
  obj['context'] = {}
  obj['context']['cluster'] = cluster['name']
  obj['context']['namespace'] = 'default'
  obj['context']['user'] = 'eks-iam-auth-%s' % cluster['name']
  return obj

def build_user(cluster):
  obj = {}
  obj['name'] = 'eks-iam-auth-%s' % cluster['name']
  obj['user'] = {}
  obj['user']['exec'] = {}
  obj['user']['exec']['apiVersion'] = "client.authentication.k8s.io/v1alpha1"
  obj['user']['exec']['command'] = "aws-iam-authenticator"
  obj['user']['exec']['args'] = ["token", "-i", cluster['name']]
  obj['user']['exec']['env'] = [
    {"name": "AWS_PROFILE", "value": os.environ['AWS_PROFILE']}
  ]
  return obj

config = build_base()

for cluster in eks.list_clusters()['clusters']:
  cluster = eks.describe_cluster(name=cluster)['cluster']

  if cluster['status'] == "ACTIVE":
    config["clusters"].append(build_cluster(cluster))
    config["users"].append(build_user(cluster))
    config["contexts"].append(build_context(cluster))

config['current-context'] = config['contexts'][0]['name'] # Just use the first context
print(yaml.dump(config))