blob: 774f407b88a1e13789cdf4ab2973178f26c26188 [file] [log] [blame]
Jack Lucasf4a00832019-03-29 16:45:20 -04001# ================================================================================
2# Copyright (c) 2019 AT&T Intellectual Property. All rights reserved.
3# ================================================================================
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15# ============LICENSE_END=========================================================
16#
17# Extract the API address and credentials provided
18# to the container by Kubernetes and push it into a
19# configmap that can be shared by other components
20# and that can be augmented with addresses and credentials
21# of remote Kubernetes clusters.
22
23from kubernetes import client, config
24import yaml
25import string
26import base64
27
28# Default values for parameters
29K8S_CENTRAL_LOCATION_ID = "central" # Used as cluster and context name in kubeconfig
30K8S_USER = "user00" # Used as user name in kubeconfig
31CONFIG_MAP_NAME = "multisite-kubeconfig-configmap" # Name of the existing ConfigMap that receives the kubeconfig
32CONFIG_MAP_KEY = "kubeconfig" # Key in ConfigMap where kubeconfig is stored
33
34def _get_config():
35 ''' Get API access configuration as provided by k8s '''
36 config.load_incluster_config()
37 cfg = client.Configuration._default
38
39 token = cfg.api_key['authorization'].split(' ')[1]
40 server = cfg.host
41 with open(cfg.ssl_ca_cert, 'r') as f:
42 ca_cert = f.read().strip()
43
44 ca_cert_string = base64.standard_b64encode(ca_cert.encode('utf-8'))
45
46 return token, server, ca_cert_string
47
48def _build_kubeconfig(location, kuser):
49 ''' Build content of a kubeconfig file using the access info provided by k8s '''
50
51 token, server, ca_cert = _get_config()
52 cluster = {"name": location, "cluster": {"server": server, "certificate-authority-data": ca_cert}}
53 user = {"name": kuser, "user": {"token": token}}
54 context = {"name": location, "context": {"cluster": location, "user": kuser}}
55
56 kubeconfig = {"apiVersion": "v1", "kind": "Config", "preferences": {}, "current-context": location}
57 kubeconfig["clusters"] = [cluster]
58 kubeconfig["users"] = [user]
59 kubeconfig["contexts"] = [context]
60
61 return kubeconfig
62
63def update_kubeconfig_config_map(namespace, config_map_name, key, kubeconfig):
64 body = client.V1ConfigMap(data={key: yaml.safe_dump(kubeconfig)})
65 client.CoreV1Api().patch_namespaced_config_map(config_map_name, namespace, body)
66
67def create_kubeconfig_file(location, user, config_file):
68 ''' Write a kubeconfig file using the API access info provided by k8s '''
69 with open(config_file, 'w') as f:
70 yaml.safe_dump(_build_kubeconfig(location, user), f)
71
72if __name__ == "__main__":
73 from optparse import OptionParser
74 parser = OptionParser()
75 parser.add_option("-l", "--location", dest="location", help="Name of central location", default=K8S_CENTRAL_LOCATION_ID)
76 parser.add_option("-u", "--user", dest="user", help="Username", default=K8S_USER)
77 parser.add_option("-n", "--namespace", dest="namespace", help="Target namespace")
78 parser.add_option("-c", "--configmap", dest="configmap", help= "ConfigMap name", default=CONFIG_MAP_NAME)
79 parser.add_option("-k", "--key", dest="key", help="ConfigMap key (filename when ConfigMap is mounted)", default=CONFIG_MAP_KEY)
80 (options, args) = parser.parse_args()
81 kubeconfig = _build_kubeconfig(options.location, options.user)
82 update_kubeconfig_config_map(options.namespace,options.configmap,options.key, kubeconfig)