Skip to content

Instantly share code, notes, and snippets.

@containerscrew
Last active May 9, 2024 13:13
Show Gist options
  • Save containerscrew/f941e9df4fa5771c70aacb9a3f622583 to your computer and use it in GitHub Desktop.
Save containerscrew/f941e9df4fa5771c70aacb9a3f622583 to your computer and use it in GitHub Desktop.
Create EKS kubeconfig using python and boto3
import boto3
import yaml
region = "eu-west-1" # change the region if needed
cluster_name = "XXXXX" # put your cluster name
config_output_file = "config.yml" # change the path or file name if needed
is_local = True # this script will be executed using ~/.aws/credentials file
# Initial boto3 session
session = boto3.Session(region_name=region)
# If you are using this script inside a k8s pod or other resource of AWS that has an attached role, use this method.
def client_assuming_role(ses):
sts = ses.client("sts")
response = sts.assume_role(
RoleArn="your-role-arn",
RoleSessionName="my-custom-session"
)
new_session = boto3.Session(aws_access_key_id=response['Credentials']['AccessKeyId'],
aws_secret_access_key=response['Credentials']['SecretAccessKey'],
aws_session_token=response['Credentials']['SessionToken'])
return new_session.client("eks")
# Instance eks_client
if is_local:
eks_client = session.client("eks")
else:
eks_client = client_assuming_role(session)
# Cluster details
cluster = eks_client.describe_cluster(name=cluster_name)
cluster_cert = cluster["cluster"]["certificateAuthority"]["data"]
cluster_ep = cluster["cluster"]["endpoint"]
cluster_arn = cluster["cluster"]["arn"]
# build the cluster config hash
cluster_config = {
"apiVersion": "v1",
"kind": "Config",
"clusters": [
{
"cluster": {
"server": str(cluster_ep),
"certificate-authority-data": str(cluster_cert)
},
"name": str(cluster_arn),
}
],
"contexts": [
{
"context": {
"cluster": str(cluster_arn),
"user": str(cluster_arn),
},
"name": str(cluster_arn),
}
],
"current-context": str(cluster_arn),
"preferences": {},
"users": [
{
"name": str(cluster_arn),
"user": {
"exec": {
"apiVersion": "client.authentication.k8s.io/v1beta1",
"command": "aws",
"args": [
"--region",
region,
"eks",
"get-token",
"--cluster-name",
cluster_name,
"--output",
"json"
],
}
}
}
]
}
# Write in YAML.
config_text = yaml.dump(cluster_config, default_flow_style=False)
open(config_output_file, "w").write(config_text)
print(f"Kubeconfig created for {cluster_name} in {config_output_file}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment