Python kubernetes.client.Configuration() Examples
The following are 30
code examples of kubernetes.client.Configuration().
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.client
, or try the search function
.
Example #1
Source File: config.py From k8s-handle with Apache License 2.0 | 8 votes |
def k8s_client_configuration(self): for parameter, value in { KEY_K8S_MASTER_URI: self._k8s_master_uri(), KEY_K8S_TOKEN: self._k8s_token() }.items(): if value: continue raise RuntimeError( '{0} parameter is not set. Please, provide {0} via CLI, config or env.'.format(parameter)) configuration = client.Configuration() configuration.host = self._k8s_master_uri() if self._k8s_ca_base64(): configuration.ssl_ca_cert = write_file_tmp(b64decode(self._k8s_ca_base64()).encode('utf-8')) configuration.api_key = {"authorization": "Bearer " + self._k8s_token()} configuration.debug = self._k8s_handle_debug() return configuration
Example #2
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 #3
Source File: tests.py From seal with MIT License | 7 votes |
def main(): Token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJkYXNoYm9hcmQtYWRtaW4tdG9rZW4tZGhobWMiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGFzaGJvYXJkLWFkbWluIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiOThkMDcwZWItODc1Yy0xMWU5LWE1MzgtMDAwYzI5N2I0ZmU3Iiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOmRhc2hib2FyZC1hZG1pbiJ9.XDFpez2E84R_zlopt_uEHPvVGUtSavypyix6UcYJO3J4imHdJy7MEkfV-wltBA1H8x0TT2AW64rLlXaRJ8OkFWJ0myedfKdjnf7i0oLQ8j-7lw6rT3A0e2pKmpnOaBQfgzRm83-t2I5MMp3Iu9VNUiAbqQpjql4AKwRuJEEGCs99tKStUxzIsJKusmUHh9KAK4BAxySn9h16T2URZ7czLP4mty2crYWNV4KwSwFPthGhFPsl8mnet_hiV5k4me5a8frmXytOy64MmGW8w3TBgiM-7hBYSxt84QGGnyi84LU0EFgtLwBWEOTZeUKKQ6IkoAprMmNcSxX8WUJFlx_uJg" APISERVER = 'https://192.168.100.111:6443' configuration = client.Configuration() configuration.host = APISERVER configuration.verify_ssl = False configuration.api_key = {"authorization": "Bearer " + Token} client.Configuration.set_default(configuration) v1 = client.CoreV1Api() ret = v1.list_pod_for_all_namespaces(watch=False) ret1 = v1.read_namespaced_pod("nginx-58bdcbcd-z8v2s","default") print(ret1) # for i in ret.items: # print("%s\t%s\t%s" % # (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
Example #4
Source File: deployment_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() apps_v1 = client.AppsV1Api() # Uncomment the following lines to enable debug logging # c = client.Configuration() # c.debug = True # apps_v1 = client.AppsV1Api(api_client=client.ApiClient(configuration=c)) # Create a deployment object with client-python API. The deployment we # created is same as the `nginx-deployment.yaml` in the /examples folder. deployment = create_deployment_object() create_deployment(apps_v1, deployment) update_deployment(apps_v1, deployment) delete_deployment(apps_v1)
Example #5
Source File: kubernetes_utils.py From tacker with Apache License 2.0 | 6 votes |
def get_k8s_client(self, auth_plugin): config = client.Configuration() config.host = auth_plugin['auth_url'] if ('username' in auth_plugin) and ('password' in auth_plugin)\ and (auth_plugin['password'] is not None): config.username = auth_plugin['username'] config.password = auth_plugin['password'] basic_token = config.get_basic_auth_token() config.api_key['authorization'] = basic_token if 'bearer_token' in auth_plugin: config.api_key_prefix['authorization'] = 'Bearer' config.api_key['authorization'] = auth_plugin['bearer_token'] ca_cert_file = auth_plugin.get('ca_cert_file') if ca_cert_file is not None: config.ssl_ca_cert = ca_cert_file config.verify_ssl = True else: config.verify_ssl = False k8s_client = api_client.ApiClient(configuration=config) return k8s_client
Example #6
Source File: core.py From mars with Apache License 2.0 | 6 votes |
def __init__(self, k8s_config=None, k8s_namespace=None, label_selector=None): from kubernetes import config, client from gevent.threadpool import ThreadPool if k8s_config is not None: self._k8s_config = k8s_config elif os.environ.get('KUBE_API_ADDRESS'): self._k8s_config = client.Configuration() self._k8s_config.host = os.environ['KUBE_API_ADDRESS'] else: self._k8s_config = config.load_incluster_config() self._k8s_namespace = k8s_namespace or os.environ.get('MARS_K8S_POD_NAMESPACE') or 'default' self._label_selector = label_selector self._client = client.CoreV1Api(client.ApiClient(self._k8s_config)) self._pool = ThreadPool(1) self._pod_to_ep = None
Example #7
Source File: base.py From polyaxon with Apache License 2.0 | 6 votes |
def __init__( self, namespace: str = None, k8s_config: Configuration = None, in_cluster: bool = None, ): if in_cluster is None: in_cluster = settings.CLIENT_CONFIG.in_cluster if not namespace: namespace = settings.CLIENT_CONFIG.namespace self.namespace = namespace self.in_cluster = in_cluster self.k8s_config = k8s_config self._k8s_manager = None
Example #8
Source File: k8s_api.py From magnum with Apache License 2.0 | 6 votes |
def __init__(self, context, cluster): self.ca_file = None self.cert_file = None self.key_file = None if cluster.magnum_cert_ref: (self.ca_file, self.key_file, self.cert_file) = create_client_files(cluster, context) config = k8s_config.Configuration() config.host = cluster.api_address config.ssl_ca_cert = self.ca_file.name config.cert_file = self.cert_file.name config.key_file = self.key_file.name # build a connection with Kubernetes master client = ApiClient(configuration=config) super(K8sAPI, self).__init__(client)
Example #9
Source File: incluster_config_test.py From python-base with Apache License 2.0 | 6 votes |
def test_refresh_token(self): loader = self.get_test_loader() config = Configuration() loader.load_and_set(config) self.assertEqual('bearer ' + _TEST_TOKEN, config.get_api_key_with_prefix('authorization')) self.assertEqual('bearer ' + _TEST_TOKEN, loader.token) self.assertIsNotNone(loader.token_expires_at) old_token = loader.token old_token_expires_at = loader.token_expires_at loader._token_filename = self._create_file_with_temp_content( _TEST_NEW_TOKEN) self.assertEqual('bearer ' + _TEST_TOKEN, config.get_api_key_with_prefix('authorization')) loader.token_expires_at = datetime.datetime.now() self.assertEqual('bearer ' + _TEST_NEW_TOKEN, config.get_api_key_with_prefix('authorization')) self.assertEqual('bearer ' + _TEST_NEW_TOKEN, loader.token) self.assertGreater(loader.token_expires_at, old_token_expires_at)
Example #10
Source File: __init__.py From insights-core with Apache License 2.0 | 6 votes |
def __init__(self, ctx=None, cfg=None): cfg = cfg or os.environ.get("KUBECONFIG") if cfg: k8s_client = config.new_client_from_config(cfg) else: config.load_incluster_config() # makes a singleton config behind the scenes k8cfg = Configuration() # gets a copy from what was populated in the line above # NOTE this is required due to https://github.com/openshift/origin/issues/22125 k8cfg.verify_ssl = False k8s_client = ApiClient(configuration=k8cfg) # this should use the singleton produced above self.k8s = DynamicClient(k8s_client) # stole this from config.new_client_from_config
Example #11
Source File: test_k8s.py From CPU-Manager-for-Kubernetes with Apache License 2.0 | 6 votes |
def test_k8s_core_client_from_config(): with pytest.raises(ConfigException) as err: k8s.client_from_config(None) # Client from in-cluster configuration should throws error if it's not # executed within pod in Kubernetes cluster. assert err is not None # If we use valid configuration for Kubernetes client, it should be # created. config = k8sclient.Configuration() config.host = "https://somenonexistedlocation.com:443" client = k8s.client_from_config(config) with pytest.raises(MaxRetryError) as err: # It should when we will use it to call Kubernetes API. client.list_node() assert err is not None
Example #12
Source File: KubiScan.py From KubiScan with GNU General Public License v3.0 | 6 votes |
def print_join_token(): import os from api.api_client import running_in_docker_container from kubernetes.client import Configuration master_ip = Configuration().host.split(':')[1][2:] master_port = Configuration().host.split(':')[2] ca_cert = '/etc/kubernetes/pki/ca.crt' if not os.path.exists(ca_cert): ca_cert = '/etc/kubernetes/ca.crt' if running_in_docker_container(): ca_cert = '/tmp' + ca_cert join_token_path = os.path.dirname(os.path.realpath(__file__)) + '/engine/join_token.sh' tokens = engine.utils.list_boostrap_tokens_decoded() if not tokens: print("No bootstrap tokens exist") else: for token in tokens: command = 'sh ' + join_token_path + ' ' + ' '.join([master_ip, master_port, ca_cert, token]) print('\nExecute: %s' % command) os.system(command)
Example #13
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 #14
Source File: kubeapi.py From kqueen with MIT License | 6 votes |
def get_api_client(self): """ Create Kubernetes API client with configuration from string. Returns: str: Kubeconfig file path """ # This super-ugly code configuration is causes by wrong design of config-loading # functions in https://github.com/kubernetes-client/python client_config = type.__call__(client.Configuration) kubeconfig = self.cluster.get_kubeconfig() if kubeconfig is None: raise ValueError("Could not create kubernetes API client: kubeconfig is not found ") kcl = KubeConfigLoader( config_dict=kubeconfig, ) kcl.load_and_set(client_config) if self.cluster.provisioner.engine == 'kqueen.engines.OpenstackKubesprayEngine': client_config.assert_hostname = False return client.ApiClient(configuration=client_config)
Example #15
Source File: client.py From conu with GNU General Public License v3.0 | 6 votes |
def get_core_api(): """ Create instance of Core V1 API of kubernetes: https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/CoreV1Api.md :return: instance of client """ global core_api if core_api is None: config.load_kube_config() if API_KEY is not None: # Configure API key authorization: BearerToken configuration = client.Configuration() configuration.api_key['authorization'] = API_KEY configuration.api_key_prefix['authorization'] = 'Bearer' core_api = client.CoreV1Api(client.ApiClient(configuration)) else: core_api = client.CoreV1Api() return core_api
Example #16
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 #17
Source File: client.py From conu with GNU General Public License v3.0 | 6 votes |
def get_apps_api(): """ Create instance of Apps V1 API of kubernetes: https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/AppsV1Api.md :return: instance of client """ global apps_api if apps_api is None: config.load_kube_config() if API_KEY is not None: # Configure API key authorization: BearerToken configuration = client.Configuration() configuration.api_key['authorization'] = API_KEY configuration.api_key_prefix['authorization'] = 'Bearer' apps_api = client.AppsV1Api(client.ApiClient(configuration)) else: apps_api = client.AppsV1Api() return apps_api
Example #18
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 #19
Source File: core.py From seal with MIT License | 5 votes |
def get_client(self): baseurl = getattr(settings, 'APISERVER') token = getattr(settings, 'Token') aConfiguration = client.Configuration() aConfiguration.host = baseurl aConfiguration.verify_ssl = False aConfiguration.api_key = {"authorization": "Bearer " + token} aApiClient = client.ApiClient(aConfiguration) v1 = client.CoreV1Api(aApiClient) return v1
Example #20
Source File: ecrupdater.py From ecr-updater with MIT License | 5 votes |
def create_pull_secrets(): if create_missing_pull_secrets_str.lower() != 'true': return None k8s_config = Configuration() k8s_config.host = kubernetes_api_endpoint k8s_api_client = ApiClient(config=k8s_config) v1 = k8sclient.CoreV1Api(api_client=k8s_api_client) namespaces = v1.list_namespace() for namespace in namespaces.items: ns_secrets = v1.list_namespaced_secret(namespace.metadata.name) has_ecr_secret = [x for x in ns_secrets.items if x.metadata.name == pull_secret_name] if not has_ecr_secret: k8s_secret = { 'server': { 'username': 'temp', 'password': 'temp' } } b64_k8s_secret = base64.b64encode(json.dumps(k8s_secret).encode('utf-8')).decode('utf-8') secret_body = { 'kind': 'Secret', 'apiVersion': 'v1', 'metadata': { 'name': pull_secret_name, 'creationTimestamp': None }, 'data': { '.dockerconfigjson': b64_k8s_secret }, 'type': 'kubernetes.io/dockerconfigjson' } print(f'Creating secret {pull_secret_name} in namespace {namespace.metadata.name}') try: v1.create_namespaced_secret(namespace.metadata.name, secret_body) except Exception as e: print(str(e))
Example #21
Source File: python_client_base.py From magnum with Apache License 2.0 | 5 votes |
def setUp(self): super(BaseK8sTest, self).setUp() self.kube_api_url = self.cs.clusters.get(self.cluster.uuid).api_address config = k8s_config.Configuration() config.host = self.kube_api_url config.ssl_ca_cert = self.ca_file config.cert_file = self.cert_file config.key_file = self.key_file k8s_client = api_client.ApiClient(configuration=config) self.k8s_api = core_v1_api.CoreV1Api(k8s_client) # TODO(coreypobrien) https://bugs.launchpad.net/magnum/+bug/1551824 utils.wait_for_condition(self._is_api_ready, 5, 600)
Example #22
Source File: kube_config_test.py From python-base with Apache License 2.0 | 5 votes |
def test_get_api_key_with_prefix_exists(self): self.assertTrue(hasattr(Configuration, 'get_api_key_with_prefix'))
Example #23
Source File: kube_config_test.py From python-base with Apache License 2.0 | 5 votes |
def test_get_api_key_with_prefix_returns_token(self): expected_token = 'expected_token' config = Configuration() config.api_key['authorization'] = expected_token self.assertEqual(expected_token, config.get_api_key_with_prefix('authorization'))
Example #24
Source File: kube_config_test.py From python-base with Apache License 2.0 | 5 votes |
def test_auth_settings_calls_get_api_key_with_prefix(self): expected_token = 'expected_token' def fake_get_api_key_with_prefix(identifier): self.assertEqual('authorization', identifier) return expected_token config = Configuration() config.get_api_key_with_prefix = fake_get_api_key_with_prefix self.assertEqual(expected_token, config.auth_settings()['BearerToken']['value'])
Example #25
Source File: kubewatch.py From ambassador with Apache License 2.0 | 5 votes |
def get_api_resources(group, version): api_client = client.ApiClient(client.Configuration()) if api_client: try: # Sadly, the Kubernetes Python library supports a method equivalent to `kubectl api-versions` # but nothing for `kubectl api-resources`. # Here, we extracted (read copy/pasted) a sample call from ApisApi().get_api_versions() # where we use the rest ApiClient to list api resources specific to a group. path_params = {} query_params = [] header_params = {} header_params['Accept'] = api_client. \ select_header_accept(['application/json']) auth_settings = ['BearerToken'] (data) = api_client.call_api(f'/apis/{group}/{version}', 'GET', path_params, query_params, header_params, auth_settings=auth_settings, response_type='V1APIResourceList') return data[0] except ApiException as e: logger.error(f'get_api_resources {e.status}') return None
Example #26
Source File: kubewatch.py From ambassador with Apache License 2.0 | 5 votes |
def check_ingress_classes(): status = False api_client = client.ApiClient(client.Configuration()) if api_client: try: # Sadly, the Kubernetes Python library is not built with forward-compatibility in mind. # Since IngressClass is a new resource, it is not discoverable through the python wrapper apis. # Here, we extracted (read copy/pasted) a sample call from k8s_v1b1.list_ingress_for_all_namespaces() # where we use the rest ApiClient to read ingressclasses. path_params = {} query_params = [] header_params = {} header_params['Accept'] = api_client. \ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) header_params['Content-Type'] = api_client. \ select_header_content_type(['*/*']) auth_settings = ['BearerToken'] api_client.call_api('/apis/networking.k8s.io/v1beta1/ingressclasses', 'GET', path_params, query_params, header_params, auth_settings=auth_settings) status = True except ApiException as e: logger.debug(f'IngressClass check got {e.status}') return status
Example #27
Source File: kubewatch.py From ambassador with Apache License 2.0 | 5 votes |
def check_ingresses(): status = False k8s_v1b1 = client.ExtensionsV1beta1Api(client.ApiClient(client.Configuration())) if k8s_v1b1: try: if ambassador_single_namespace: k8s_v1b1.list_namespaced_ingress(ambassador_namespace) else: k8s_v1b1.list_ingress_for_all_namespaces() status = True except ApiException as e: logger.debug(f'Ingress check got {e.status}') return status
Example #28
Source File: kubewatch.py From ambassador with Apache License 2.0 | 5 votes |
def kube_v1(): # Assume we got nothin'. k8s_api = None # XXX: is there a better way to check if we are inside a cluster or not? if "KUBERNETES_SERVICE_HOST" in os.environ: # If this goes horribly wrong and raises an exception (it shouldn't), # we'll crash, and Kubernetes will kill the pod. That's probably not an # unreasonable response. config.load_incluster_config() if "AMBASSADOR_VERIFY_SSL_FALSE" in os.environ: configuration = client.Configuration() configuration.verify_ssl = False client.Configuration.set_default(configuration) k8s_api = client.CoreV1Api() else: # Here, we might be running in docker, in which case we'll likely not # have any Kube secrets, and that's OK. try: config.load_kube_config() k8s_api = client.CoreV1Api() except FileNotFoundError: # Meh, just ride through. logger.info("No K8s") pass return k8s_api
Example #29
Source File: python_client_base.py From magnum with Apache License 2.0 | 5 votes |
def setUpClass(cls): super(BaseK8sTest, cls).setUpClass() cls.kube_api_url = cls.cs.clusters.get(cls.cluster.uuid).api_address config = k8s_config.Configuration() config.host = cls.kube_api_url config.ssl_ca_cert = cls.ca_file config.cert_file = cls.cert_file config.key_file = cls.key_file k8s_client = api_client.ApiClient(configuration=config) cls.k8s_api = core_v1_api.CoreV1Api(k8s_client)
Example #30
Source File: k8s_api.py From magnum with Apache License 2.0 | 5 votes |
def __init__(self, configuration=None, header_name=None, header_value=None, cookie=None): if configuration is None: configuration = k8s_configuration.Configuration() self.configuration = configuration self.rest_client = rest.RESTClientObject(configuration) self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value self.cookie = cookie