Skip to content

Instantly share code, notes, and snippets.

@lcasartelli
Created August 26, 2021 15:15
Show Gist options
  • Save lcasartelli/d0f030d883346cfa4b8fb9487e217508 to your computer and use it in GitHub Desktop.
Save lcasartelli/d0f030d883346cfa4b8fb9487e217508 to your computer and use it in GitHub Desktop.
Generate a valid kubeconfig file for EKS cluster
import json
import boto3
from datetime import datetime, timedelta
from botocore import session
from awscli.customizations.eks.get_token import STSClientFactory, TokenGenerator, TOKEN_EXPIRATION_MINS
def _get_expiration_time():
t_exp = datetime.utcnow() + timedelta(minutes=TOKEN_EXPIRATION_MINS)
return t_exp.strftime('%Y-%m-%dT%H:%M:%SZ')
def _get_token(cluster_name: str):
work_session = session.get_session()
client_factory = STSClientFactory(work_session)
sts_client = client_factory.get_sts_client()
token = TokenGenerator(sts_client).get_token(cluster_name)
token_payload = {
"kind": "ExecCredential",
"apiVersion": "client.authentication.k8s.io/v1alpha1",
"spec": {},
"status": {
"expirationTimestamp": _get_expiration_time(),
"token": token
}
}
return json.dumps(json.dumps(token_payload))
def get_kube_config(cluster_name: str) -> dict:
eks_client = boto3.client('eks', region_name='us-east-2')
cluster_response = eks_client.describe_cluster(
name=cluster_name
)['cluster']
return f'''
apiVersion: v1
clusters:
- cluster:
server: {cluster_response["endpoint"]}
certificate-authority-data: {cluster_response["certificateAuthority"]["data"]}
name: kubernetes
contexts:
- context:
cluster: kubernetes
user: aws
name: aws
current-context: aws
kind: Config
preferences: {{}}
users:
- name: aws
user:
exec:
apiVersion: client.authentication.k8s.io/v1alpha1
args:
- {_get_token(cluster_name)}
command: echo
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment