Python kubernetes.config.list_kube_config_contexts() Examples

The following are 9 code examples of kubernetes.config.list_kube_config_contexts(). 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 12 votes vote down vote up
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: pick_kube_config_context.py    From python with Apache License 2.0 8 votes vote down vote up
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 #3
Source File: kubernetes_orchestrator.py    From coach with Apache License 2.0 6 votes vote down vote up
def __init__(self, params: KubernetesParameters):
        """
        :param params: The Kubernetes parameters which are used for deploying the components in Coach. These parameters
        include namespace and kubeconfig.
        """

        super().__init__(params)
        self.params = params
        if self.params.kubeconfig:
            k8sconfig.load_kube_config()
        else:
            k8sconfig.load_incluster_config()

        if not self.params.namespace:
            _, current_context = k8sconfig.list_kube_config_contexts()
            self.params.namespace = current_context['context']['namespace']

        if os.environ.get('http_proxy'):
            k8sclient.Configuration._default.proxy = os.environ.get('http_proxy')

        self.params.memory_backend_parameters.orchestrator_params = {'namespace': self.params.namespace}
        self.memory_backend = get_memory_backend(self.params.memory_backend_parameters)

        self.params.data_store_params.orchestrator_params = {'namespace': self.params.namespace}
        self.params.data_store_params.namespace = self.params.namespace
        self.data_store = get_data_store(self.params.data_store_params)

        if self.params.data_store_params.store_type == "s3":
            self.s3_access_key = None
            self.s3_secret_key = None
            if self.params.data_store_params.creds_file:
                s3config = ConfigParser()
                s3config.read(self.params.data_store_params.creds_file)
                try:
                    self.s3_access_key = s3config.get('default', 'aws_access_key_id')
                    self.s3_secret_key = s3config.get('default', 'aws_secret_access_key')
                except Error as e:
                    print("Error when reading S3 credentials file: %s", e)
            else:
                self.s3_access_key = os.environ.get('ACCESS_KEY_ID')
                self.s3_secret_key = os.environ.get('SECRET_ACCESS_KEY') 
Example #4
Source File: kubernetes_client.py    From jupyterhub-k8s with Apache License 2.0 6 votes vote down vote up
def configure_new_context(self, new_context):
		""" Loads .kube config to instantiate kubernetes
		with specified context"""
		contexts, _ = config.list_kube_config_contexts()
		try:
			contexts = [c['name'] for c in contexts]
			context_to_activate = list(
				filter(lambda context: new_context in context, contexts))
			assert len(context_to_activate) == 1  # avoid undefined behavior
			context_to_activate = context_to_activate[0]
		except (TypeError, IndexError):
			backup_logger.exception("Could not load context %s\n" % new_context)
			sys.exit(1)
		except AssertionError:
			backup_logger.fatal("Vague context specification")
			sys.exit(1)
		config.load_kube_config(context=context_to_activate)
		backup_logger.info("Successfully loaded %s context" % new_context)
		return context_to_activate 
Example #5
Source File: __init__.py    From k8s-handle with Apache License 2.0 5 votes vote down vote up
def _handler_provision(command, resources, priority_evaluator, use_kubeconfig, sync_mode, show_logs):
    kubeconfig_namespace = None

    if priority_evaluator.environment_deprecated():
        log.warning("K8S_HOST and K8S_CA environment variables support is deprecated "
                    "and will be discontinued in the future. Use K8S_MASTER_URI and K8S_CA_BASE64 instead.")

    # INFO rvadim: https://github.com/kubernetes-client/python/issues/430#issuecomment-359483997
    if use_kubeconfig:
        try:
            load_kube_config()
            kubeconfig_namespace = list_kube_config_contexts()[1].get('context').get('namespace')
        except Exception as e:
            raise RuntimeError(e)
    else:
        client.Configuration.set_default(priority_evaluator.k8s_client_configuration())

    settings.K8S_NAMESPACE = priority_evaluator.k8s_namespace_default(kubeconfig_namespace)
    log.info('Default namespace "{}"'.format(settings.K8S_NAMESPACE))

    if not settings.K8S_NAMESPACE:
        log.info("Default namespace is not set. "
                 "This may lead to provisioning error, if namespace is not set for each resource.")

    try:
        deprecation_checker = ApiDeprecationChecker(client.VersionApi().get_code().git_version[1:])
        available_checker = ResourceAvailabilityChecker(make_resource_getters_list())

        for resource in resources:
            deprecation_checker.run(resource)
            available_checker.run(resource)
    except client.api_client.ApiException:
        log.warning("Error while getting API version, deprecation check will be skipped.")

    provisioner = Provisioner(command, sync_mode, show_logs)

    for resource in resources:
        provisioner.run(resource) 
Example #6
Source File: multiple_clusters.py    From python with Apache License 2.0 5 votes vote down vote up
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'])
    cluster1, first_index = pick(contexts, title="Pick the first context",
                                 default_index=active_index)
    cluster2, _ = pick(contexts, title="Pick the second context",
                       default_index=first_index)

    client1 = client.CoreV1Api(
        api_client=config.new_client_from_config(context=cluster1))
    client2 = client.CoreV1Api(
        api_client=config.new_client_from_config(context=cluster2))

    print("\nList of pods on %s:" % cluster1)
    for i in client1.list_pod_for_all_namespaces().items:
        print("%s\t%s\t%s" %
              (i.status.pod_ip, i.metadata.namespace, i.metadata.name))

    print("\n\nList of pods on %s:" % cluster2)
    for i in client2.list_pod_for_all_namespaces().items:
        print("%s\t%s\t%s" %
              (i.status.pod_ip, i.metadata.namespace, i.metadata.name)) 
Example #7
Source File: tools.py    From sparrow with GNU General Public License v3.0 5 votes vote down vote up
def k8s_conf():
    config_file="%s/../conf/k8s.conf" % app.root_path
    contexts, active_context = config.list_kube_config_contexts(config_file)
    contexts = [context['name'] for context in contexts]
    config.load_kube_config(config_file, context=active_context['name'])
    return(config,contexts,config_file) 
Example #8
Source File: k8s.py    From nephos with Apache License 2.0 5 votes vote down vote up
def context_get():
    """Obtain active K8S context.

    Returns:
        object: Active context.
    """
    _, active_context = config.list_kube_config_contexts()
    logging.debug(pretty_print(json.dumps(active_context)))
    return active_context


# Namespaces 
Example #9
Source File: __init__.py    From kcli with Apache License 2.0 4 votes vote down vote up
def __init__(self, token=None, ca_file=None, context=None, host='127.0.0.1', port=443, user='root', debug=False,
                 namespace=None, readwritemany=False):
        self.host = host
        self.port = port
        self.user = user
        self.ca_file = ca_file
        self.readwritemany = readwritemany
        self.context = context
        self.accessmode = 'ReadWriteMany' if readwritemany else 'ReadWriteOnce'
        self.conn = 'OK'
        self.namespace = namespace
        self.token = token
        api_client = None
        if host is not None and port is not None and token is not None:
            configuration = client.Configuration()
            configuration.host = "https://%s:%s" % (host, port)
            configuration.api_key = {"authorization": "Bearer " + token}
            if ca_file is not None:
                configuration.ssl_ca_cert = ca_file
            else:
                configuration.verify_ssl = False
            api_client = client.ApiClient(configuration)
        else:
            contexts, current = config.list_kube_config_contexts()
            if context is not None:
                contexts = [entry for entry in contexts if entry['name'] == context]
                if contexts:
                    context = contexts[0]
                    contextname = context['name']
                else:
                    self.conn = None
            else:
                context = current
                contextname = current['name']
            self.contextname = contextname
            config.load_kube_config(context=contextname)
            if namespace is None and 'namespace' in context['context']:
                self.namespace = context['context']['namespace']
            if 'cluster' in context['context'] and ':' in context['context']['cluster']:
                self.host = context['context']['cluster'].split(':')[0].replace('-', '.')
        self.core = client.CoreV1Api(api_client=api_client)
        self.v1beta = client.ExtensionsV1beta1Api(api_client=api_client)
        self.storageapi = client.StorageV1Api(api_client=api_client)
        self.api_client = api_client
        self.debug = debug
        if self.namespace is None:
            self.namespace = 'default'
        return