Skip to content

Instantly share code, notes, and snippets.

@monester
Created August 28, 2019 04:57
Show Gist options
  • Save monester/d389657c707ad203f2865afbfbc92759 to your computer and use it in GitHub Desktop.
Save monester/d389657c707ad203f2865afbfbc92759 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import os
import json
from subprocess import check_output, CalledProcessError
from configparser import ConfigParser
def kubectl(command, context=None, output=True):
context = f'--context={context}' if context else ''
output = '-o=json' if output else ''
command = f'kubectl {context} {command} {output}'
result = check_output(command, shell=True)
if output:
result = json.loads(result.decode('utf-8'))
return result
def main():
config = ConfigParser()
config.read(os.path.expanduser('~/.kube/rancher-clusters.ini'))
existing_contexts = check_output('kubectl config get-contexts -o name', shell=True).decode('utf-8').split('\n')
for root_cluster in config.sections():
try:
rancher_config = kubectl('config view --minify', context=root_cluster)
except CalledProcessError:
print(f'Rancher cluster {root_cluster} not found in ~/.kube/config')
continue
username = rancher_config['users'][0]['name']
rancher_url_prefix = '/'.join(rancher_config['clusters'][0]['cluster']['server'].split('/')[:-1])
clusters = kubectl('get clusters', context=root_cluster)['items']
rancher_clusters = set()
for cluster in clusters:
cluster_name = root_cluster + "-" + cluster['spec']['displayName']
cluster_id = cluster['metadata']['name']
rancher_clusters.add(cluster_name)
# skip root cluster as it is already defined
if cluster_id == 'local':
continue
print(cluster['metadata']['name'], cluster['spec']['displayName'])
kubectl(f'config set-cluster {cluster_name} --server {rancher_url_prefix}/{cluster_id}', output=False)
kubectl(f'config set-context {cluster_name} --cluster {cluster_name} --user {username}', output=False)
for cluster_name in existing_contexts:
if cluster_name not in rancher_clusters and cluster_name != root_cluster and cluster_name.startswith(root_cluster):
print(f'Removing missing {cluster_name}')
check_output(f'kubectl config delete-context {cluster_name}', shell=True)
check_output(f'kubectl config delete-cluster {cluster_name}', shell=True)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment