Python kubernetes.config.load_kube_config() Examples
The following are 30
code examples of kubernetes.config.load_kube_config().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
kubernetes.config
, or try the search function
.
Example #1
Source File: pod_config_list.py From python with Apache License 2.0 | 13 votes |
def main(): contexts, active_context = config.list_kube_config_contexts() if not contexts: print("Cannot find any context in kube-config file.") return contexts = [context['name'] for context in contexts] active_index = contexts.index(active_context['name']) option, _ = pick(contexts, title="Pick the context to load", default_index=active_index) # Configs can be set in Configuration class directly or using helper # utility config.load_kube_config(context=option) print("Active host is %s" % configuration.Configuration().host) v1 = client.CoreV1Api() print("Listing pods with their IPs:") ret = v1.list_pod_for_all_namespaces(watch=False) for item in ret.items: print( "%s\t%s\t%s" % (item.status.pod_ip, item.metadata.namespace, item.metadata.name))
Example #2
Source File: kubernetes_tools.py From paasta with Apache License 2.0 | 9 votes |
def __init__(self) -> None: kube_config.load_kube_config( config_file=os.environ.get("KUBECONFIG", KUBE_CONFIG_PATH), context=os.environ.get("KUBECONTEXT"), ) models.V1beta1PodDisruptionBudgetStatus.disrupted_pods = property( fget=lambda *args, **kwargs: models.V1beta1PodDisruptionBudgetStatus.disrupted_pods( *args, **kwargs ), fset=_set_disrupted_pods, ) self.deployments = kube_client.AppsV1Api() self.core = kube_client.CoreV1Api() self.policy = kube_client.PolicyV1beta1Api() self.apiextensions = kube_client.ApiextensionsV1beta1Api() self.custom = kube_client.CustomObjectsApi() self.autoscaling = kube_client.AutoscalingV2beta1Api() self.request = kube_client.ApiClient().request
Example #3
Source File: k8s.py From eks-rolling-update with Apache License 2.0 | 8 votes |
def get_k8s_nodes(exclude_node_label_key=app_config["EXCLUDE_NODE_LABEL_KEY"]): """ Returns a list of kubernetes nodes """ try: config.load_incluster_config() except config.ConfigException: try: config.load_kube_config() except config.ConfigException: raise Exception("Could not configure kubernetes python client") k8s_api = client.CoreV1Api() logger.info("Getting k8s nodes...") response = k8s_api.list_node() if exclude_node_label_key is not None: nodes = [] for node in response.items: if exclude_node_label_key not in node.metadata.labels: nodes.append(node) response.items = nodes logger.info("Current k8s node count is {}".format(len(response.items))) return response.items
Example #4
Source File: pick_kube_config_context.py From python with Apache License 2.0 | 8 votes |
def main(): contexts, active_context = config.list_kube_config_contexts() if not contexts: print("Cannot find any context in kube-config file.") return contexts = [context['name'] for context in contexts] active_index = contexts.index(active_context['name']) option, _ = pick(contexts, title="Pick the context to load", default_index=active_index) # Configs can be set in Configuration class directly or using helper # utility config.load_kube_config(context=option) print("Active host is %s" % configuration.Configuration().host) v1 = client.CoreV1Api() print("Listing pods with their IPs:") ret = v1.list_pod_for_all_namespaces(watch=False) for item in ret.items: print( "%s\t%s\t%s" % (item.status.pod_ip, item.metadata.namespace, item.metadata.name))
Example #5
Source File: kubernetes.py From airflow with Apache License 2.0 | 7 votes |
def get_conn(self): """ Returns kubernetes api session for use with requests """ connection = self.get_connection(self.conn_id) extras = connection.extra_dejson if extras.get("extra__kubernetes__in_cluster"): self.log.debug("loading kube_config from: in_cluster configuration") config.load_incluster_config() elif extras.get("extra__kubernetes__kube_config") is None: self.log.debug("loading kube_config from: default file") config.load_kube_config() else: with tempfile.NamedTemporaryFile() as temp_config: self.log.debug("loading kube_config from: connection kube_config") temp_config.write(extras.get("extra__kubernetes__kube_config").encode()) temp_config.flush() config.load_kube_config(temp_config.name) return client.ApiClient()
Example #6
Source File: k8s.py From eks-rolling-update with Apache License 2.0 | 7 votes |
def delete_node(node_name): """ Deletes a kubernetes node from the cluster """ try: config.load_incluster_config() except config.ConfigException: try: config.load_kube_config() except config.ConfigException: raise Exception("Could not configure kubernetes python client") configuration = client.Configuration() # create an instance of the API class k8s_api = client.CoreV1Api(client.ApiClient(configuration)) logger.info("Deleting k8s node {}...".format(node_name)) try: if not app_config['DRY_RUN']: k8s_api.delete_node(node_name) else: k8s_api.delete_node(node_name, dry_run="true") logger.info("Node deleted") except ApiException as e: logger.info("Exception when calling CoreV1Api->delete_node: {}".format(e))
Example #7
Source File: node_labels.py From python with Apache License 2.0 | 7 votes |
def main(): config.load_kube_config() api_instance = client.CoreV1Api() body = { "metadata": { "labels": { "foo": "bar", "baz": None} } } api_response = api_instance.patch_node("minikube", body) pprint(api_response)
Example #8
Source File: reflector.py From kubespawner with BSD 3-Clause "New" or "Revised" License | 7 votes |
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Load kubernetes config here, since this is a Singleton and # so this __init__ will be run way before anything else gets run. try: config.load_incluster_config() except config.ConfigException: config.load_kube_config() self.api = shared_client(self.api_group_name) # FIXME: Protect against malicious labels? self.label_selector = ','.join(['{}={}'.format(k, v) for k, v in self.labels.items()]) self.field_selector = ','.join(['{}={}'.format(k, v) for k, v in self.fields.items()]) self.first_load_future = Future() self._stop_event = threading.Event() self.start()
Example #9
Source File: engine.py From ansible-playbook-bundle with GNU General Public License v2.0 | 7 votes |
def create_service_account(name, namespace): print("Creating service account in {}".format(namespace)) try: kubernetes_config.load_kube_config() api = kubernetes_client.CoreV1Api() api.create_namespaced_service_account( namespace, { 'apiVersion': 'v1', 'kind': 'ServiceAccount', 'metadata': { 'name': name, 'namespace': namespace, }, } ) print("Created service account") return name except ApiException as e: if e.status == 409: print("Service account {} already exists".format(name)) return name raise e
Example #10
Source File: api_discovery.py From python with Apache License 2.0 | 7 votes |
def main(): # Configs can be set in Configuration class directly or using helper # utility. If no argument provided, the config will be loaded from # default location. config.load_kube_config() print("Supported APIs (* is preferred version):") print("%-40s %s" % ("core", ",".join(client.CoreApi().get_api_versions().versions))) for api in client.ApisApi().get_api_versions().groups: versions = [] for v in api.versions: name = "" if v.version == api.preferred_version.version and len( api.versions) > 1: name += "*" name += v.version versions.append(name) print("%-40s %s" % (api.name, ",".join(versions)))
Example #11
Source File: engine.py From ansible-playbook-bundle with GNU General Public License v2.0 | 7 votes |
def get_registry_service_ip(namespace, svc_name): ip = None try: openshift_config.load_kube_config() api = kubernetes_client.CoreV1Api() service = api.read_namespaced_service(namespace=namespace, name=svc_name) if service is None: print("Couldn't find docker-registry service in namespace default. Erroring.") return None if service.spec.ports == []: print("Service spec appears invalid. Erroring.") return None ip = service.spec.cluster_ip + ":" + str(service.spec.ports[0].port) print("Found registry IP at: " + ip) except ApiException as e: print("Exception occurred trying to find %s service in namespace %s: %s" % (svc_name, namespace, e)) return None return ip
Example #12
Source File: engine.py From ansible-playbook-bundle with GNU General Public License v2.0 | 7 votes |
def create_project(project): print("Creating project {}".format(project)) try: openshift_config.load_kube_config() api = openshift_client.OapiApi() api.create_project_request({ 'apiVersion': 'v1', 'kind': 'ProjectRequest', 'metadata': { 'name': project } }) print("Created project") # TODO: Evaluate the project request to get the actual project name return project except ApiException as e: if e.status == 409: print("Project {} already exists".format(project)) return project else: raise e
Example #13
Source File: deploy_utils.py From aws-eks-deep-learning-benchmark with Apache License 2.0 | 7 votes |
def copy_job_config(src_dir, namespace): config.load_kube_config() v1 = k8s_client.CoreV1Api() nfs_server_pod = None ret = v1.list_namespaced_pod(namespace, watch=False) for i in ret.items: if(i.metadata.labels.get("role") != None) & (i.metadata.labels.get("role") == "nfs-server"): nfs_server_pod = i.metadata.name if nfs_server_pod is None: logging.info("nfs server pod NOT found") return 0 cmd = "kubectl -n " + namespace + " exec " + nfs_server_pod + " -- mkdir -p /exports/config" util.run(cmd.split(), cwd=src_dir) cmd = "kubectl cp examples/tf_cnn_benchmarks/job_config.yaml " + namespace + \ "/" + nfs_server_pod + ":/exports/config/job-config.yaml" util.run(cmd.split(), cwd=src_dir) return 1
Example #14
Source File: engine.py From ansible-playbook-bundle with GNU General Public License v2.0 | 7 votes |
def watch_pod(name, namespace): kubernetes_config.load_kube_config() api = kubernetes_client.CoreV1Api() while True: sleep(WATCH_POD_SLEEP) pod_status = api.read_namespaced_pod(name, namespace).status pod_phase = pod_status.phase print("Pod in phase: {}".format(pod_phase)) if pod_phase == 'Succeeded' or pod_phase == 'Failed': print(api.read_namespaced_pod_log(name, namespace)) return pod_phase if pod_phase == 'Pending': try: reason = pod_status.container_statuses[0].state.waiting.reason except ApiException: pass if reason == 'ImagePullBackOff': raise ApiException("APB failed {} - check name".format(reason))
Example #15
Source File: _k8s_job_helper.py From pipelines with Apache License 2.0 | 7 votes |
def _configure_k8s(self): k8s_config_file = os.environ.get('KUBECONFIG') if k8s_config_file: try: logging.info('Loading kubernetes config from the file %s', k8s_config_file) config.load_kube_config(config_file=k8s_config_file) except Exception as e: raise RuntimeError('Can not load kube config from the file %s, error: %s', k8s_config_file, e) else: try: config.load_incluster_config() logging.info('Initialized with in-cluster config.') except: logging.info('Cannot find in-cluster config, trying the local kubernetes config. ') try: config.load_kube_config() logging.info('Found local kubernetes config. Initialized with kube_config.') except: raise RuntimeError('Forgot to run the gcloud command? Check out the link: \ https://cloud.google.com/kubernetes-engine/docs/how-to/cluster-access-for-kubectl for more information') self._api_client = k8s_client.ApiClient() self._corev1 = k8s_client.CoreV1Api(self._api_client) return True
Example #16
Source File: driver.py From vitrage with Apache License 2.0 | 7 votes |
def _k8s_client(): try: if not CONF.kubernetes.config_file: LOG.warning('kubernetes config file is not defined') return kubeconf = CONF.kubernetes.config_file config.load_kube_config(config_file=kubeconf) k8s_client = client.CoreV1Api() if k8s_client is None: LOG.warning('k8s client returns None') return return k8s_client except Exception: LOG.exception('Create k8s client - Got Exception')
Example #17
Source File: manager.py From polyaxon with Apache License 2.0 | 7 votes |
def __init__(self, k8s_config=None, namespace="default", in_cluster=False): if not k8s_config: if in_cluster: config.load_incluster_config() else: config.load_kube_config() self.api_client = None else: self.api_client = client.api_client.ApiClient(configuration=k8s_config) self._k8s_api = None self._k8s_batch_api = None self._k8s_apps_api = None self._k8s_beta_api = None self._networking_v1_beta1_api = None self._k8s_custom_object_api = None self._k8s_version_api = None self.namespace = namespace self.in_cluster = in_cluster
Example #18
Source File: k8s.py From armada with Apache License 2.0 | 6 votes |
def __init__(self, bearer_token=None): ''' Initialize connection to Kubernetes ''' self.bearer_token = bearer_token api_client = None try: config.load_incluster_config() except config.config_exception.ConfigException: config.load_kube_config() if self.bearer_token: # Configure API key authorization: Bearer Token configuration = client.Configuration() configuration.api_key_prefix['authorization'] = 'Bearer' configuration.api_key['authorization'] = self.bearer_token api_client = client.ApiClient(configuration) self.client = client.CoreV1Api(api_client) self.batch_api = client.BatchV1Api(api_client) self.batch_v1beta1_api = client.BatchV1beta1Api(api_client) self.custom_objects = client.CustomObjectsApi(api_client) self.api_extensions = client.ApiextensionsV1beta1Api(api_client) self.extension_api = client.ExtensionsV1beta1Api(api_client) self.apps_v1_api = client.AppsV1Api(api_client)
Example #19
Source File: deployment_create.py From python with Apache License 2.0 | 6 votes |
def main(): # Configs can be set in Configuration class directly or using helper # utility. If no argument provided, the config will be loaded from # default location. config.load_kube_config() with open(path.join(path.dirname(__file__), "nginx-deployment.yaml")) as f: dep = yaml.safe_load(f) k8s_apps_v1 = client.AppsV1Api() resp = k8s_apps_v1.create_namespaced_deployment( body=dep, namespace="default") print("Deployment created. status='%s'" % resp.metadata.name)
Example #20
Source File: job_crud.py From python with Apache License 2.0 | 6 votes |
def main(): # Configs can be set in Configuration class directly or using helper # utility. If no argument provided, the config will be loaded from # default location. config.load_kube_config() batch_v1 = client.BatchV1Api() # Create a job object with client-python API. The job we # created is same as the `pi-job.yaml` in the /examples folder. job = create_job_object() create_job(batch_v1, job) update_job(batch_v1, job) delete_job(batch_v1)
Example #21
Source File: ingress_create.py From python with Apache License 2.0 | 6 votes |
def main(): # Fetching and loading local Kubernetes Information config.load_kube_config() apps_v1_api = client.AppsV1Api() networking_v1_beta1_api = client.NetworkingV1beta1Api() create_deployment(apps_v1_api) create_service() create_ingress(networking_v1_beta1_api)
Example #22
Source File: pod_exec.py From python with Apache License 2.0 | 6 votes |
def main(): config.load_kube_config() c = Configuration() c.assert_hostname = False Configuration.set_default(c) core_v1 = core_v1_api.CoreV1Api() exec_commands(core_v1)
Example #23
Source File: k8s.py From armada with Apache License 2.0 | 6 votes |
def __init__(self): ''' Initialize connection to Kubernetes ''' try: config.load_incluster_config() except config.config_exception.ConfigException: config.load_kube_config() self.client = client.CoreV1Api() self.batch_api = client.BatchV1Api() self.batch_v1beta1_api = client.BatchV1beta1Api() self.extension_api = client.ExtensionsV1beta1Api()
Example #24
Source File: kubernetes_resources.py From inference-model-manager with Apache License 2.0 | 6 votes |
def get_k8s_configuration(): try: configuration = config.load_kube_config() except Exception: configuration = config.load_incluster_config() return configuration
Example #25
Source File: conftest.py From inference-model-manager with Apache License 2.0 | 6 votes |
def configuration(): return config.load_kube_config()
Example #26
Source File: conftest.py From inference-model-manager with Apache License 2.0 | 6 votes |
def list_namespaces(): try: k8s_client = client.CoreV1Api(client.ApiClient(config.load_kube_config())) api_response = k8s_client.list_namespace() except ApiException as e: api_response = e print("Exception when calling CoreV1Api->list_namespace: %s\n" % e) return api_response
Example #27
Source File: kube.py From reckoner with Apache License 2.0 | 6 votes |
def __load_config(self): """ Protected method to load kubernetes config""" try: config.load_kube_config() self.v1client = client.CoreV1Api() except Exception as e: logging.error('Unable to load kubernetes configuration') logging.debug(traceback.format_exc()) raise e
Example #28
Source File: kube_client.py From airflow with Apache License 2.0 | 6 votes |
def _get_kube_config(in_cluster: bool, cluster_context: Optional[str], config_file: Optional[str]) -> Optional[Configuration]: if in_cluster: # load_incluster_config set default configuration with config populated by k8s config.load_incluster_config() return None else: # this block can be replaced with just config.load_kube_config once # refresh_config module is replaced with upstream fix cfg = RefreshConfiguration() load_kube_config( client_configuration=cfg, config_file=config_file, context=cluster_context) return cfg
Example #29
Source File: k8s.py From eks-rolling-update with Apache License 2.0 | 6 votes |
def modify_k8s_autoscaler(action): """ Pauses or resumes the Kubernetes autoscaler """ try: config.load_incluster_config() except config.ConfigException: try: config.load_kube_config() except config.ConfigException: raise Exception("Could not configure kubernetes python client") # Configure API key authorization: BearerToken configuration = client.Configuration() # create an instance of the API class k8s_api = client.AppsV1Api(client.ApiClient(configuration)) if action == 'pause': logger.info('Pausing k8s autoscaler...') body = {'spec': {'replicas': 0}} elif action == 'resume': logger.info('Resuming k8s autoscaler...') body = {'spec': {'replicas': app_config['K8S_AUTOSCALER_REPLICAS']}} else: logger.info('Invalid k8s autoscaler option') sys.exit(1) try: k8s_api.patch_namespaced_deployment( app_config['K8S_AUTOSCALER_DEPLOYMENT'], app_config['K8S_AUTOSCALER_NAMESPACE'], body ) logger.info('K8s autoscaler modified to replicas: {}'.format(body['spec']['replicas'])) except ApiException as e: logger.info('Scaling of k8s autoscaler failed. Error code was {}, {}. Exiting.'.format(e.reason, e.body)) sys.exit(1)
Example #30
Source File: pod_namespace_watch.py From python with Apache License 2.0 | 6 votes |
def main(): # Configs can be set in Configuration class directly or using helper # utility. If no argument provided, the config will be loaded from # default location. config.load_kube_config() v1 = client.CoreV1Api() count = 10 w = watch.Watch() for event in w.stream(v1.list_namespace, timeout_seconds=10): print("Event: %s %s" % (event['type'], event['object'].metadata.name)) count -= 1 if not count: w.stop() print("Finished namespace stream.") for event in w.stream(v1.list_pod_for_all_namespaces, timeout_seconds=10): print("Event: %s %s %s" % ( event['type'], event['object'].kind, event['object'].metadata.name) ) count -= 1 if not count: w.stop() print("Finished pod stream.")