本文整理汇总了Python中kubernetes.config.list_kube_config_contexts方法的典型用法代码示例。如果您正苦于以下问题:Python config.list_kube_config_contexts方法的具体用法?Python config.list_kube_config_contexts怎么用?Python config.list_kube_config_contexts使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类kubernetes.config
的用法示例。
在下文中一共展示了config.list_kube_config_contexts方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import list_kube_config_contexts [as 别名]
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))
示例2: configure_new_context
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import list_kube_config_contexts [as 别名]
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
示例3: _handler_provision
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import list_kube_config_contexts [as 别名]
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)
示例4: main
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import list_kube_config_contexts [as 别名]
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))
示例5: k8s_conf
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import list_kube_config_contexts [as 别名]
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)
示例6: context_get
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import list_kube_config_contexts [as 别名]
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
示例7: __init__
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import list_kube_config_contexts [as 别名]
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')
示例8: __init__
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import list_kube_config_contexts [as 别名]
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