Python kubernetes.client.ApiClient() Examples

The following are 30 code examples of kubernetes.client.ApiClient(). 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: kubernetes_tools.py    From paasta with Apache License 2.0 9 votes vote down vote up
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 #2
Source File: kubernetes.py    From airflow with Apache License 2.0 7 votes vote down vote up
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 #3
Source File: _k8s_job_helper.py    From pipelines with Apache License 2.0 7 votes vote down vote up
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 #4
Source File: test_utils.py    From python with Apache License 2.0 6 votes vote down vote up
def test_create_from_multi_resource_yaml(self):
        """
        Should be able to create a service and a replication controller
        from a multi-resource yaml file
        """
        k8s_client = client.api_client.ApiClient(configuration=self.config)
        utils.create_from_yaml(
            k8s_client, self.path_prefix + "multi-resource.yaml")
        core_api = client.CoreV1Api(k8s_client)
        svc = core_api.read_namespaced_service(name="mock",
                                               namespace="default")
        self.assertIsNotNone(svc)
        ctr = core_api.read_namespaced_replication_controller(
            name="mock", namespace="default")
        self.assertIsNotNone(ctr)
        core_api.delete_namespaced_replication_controller(
            name="mock", namespace="default", body={})
        core_api.delete_namespaced_service(name="mock",
                                           namespace="default", body={}) 
Example #5
Source File: test_utils.py    From python with Apache License 2.0 6 votes vote down vote up
def test_create_general_list_from_yaml(self):
        """
        Should be able to create a service and a deployment
        from a kind: List yaml file
        """
        k8s_client = client.api_client.ApiClient(configuration=self.config)
        utils.create_from_yaml(
            k8s_client, self.path_prefix + "list.yaml")
        core_api = client.CoreV1Api(k8s_client)
        ext_api = client.AppsV1Api(k8s_client)
        svc = core_api.read_namespaced_service(name="list-service-test",
                                               namespace="default")
        self.assertIsNotNone(svc)
        dep = ext_api.read_namespaced_deployment(name="list-deployment-test",
                                                 namespace="default")
        self.assertIsNotNone(dep)
        core_api.delete_namespaced_service(name="list-service-test",
                                           namespace="default", body={})
        ext_api.delete_namespaced_deployment(name="list-deployment-test",
                                             namespace="default", body={}) 
Example #6
Source File: pipeline.py    From freight with Apache License 2.0 6 votes vote down vote up
def load_kube_credentials(config: Dict[str, Any]) -> ApiClient:
    # If a context is specified, attempt to use this first.
    try:
        return new_client_from_config(context=config["context"])
    except KeyError:
        pass

    try:
        credentials = config["credentials"]
    except KeyError:
        raise AuthenticationError("Missing kubernetes context.")

    if credentials["kind"] not in ("gcloud",):
        raise AuthenticationError(f"Unknown kubernetes kind: {credentials['kind']}")

    return load_kube_credentials_gcloud(credentials) 
Example #7
Source File: __init__.py    From insights-core with Apache License 2.0 6 votes vote down vote up
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 #8
Source File: rhopenshift.py    From wrapanapi with MIT License 6 votes vote down vote up
def _connect(self):
        url = '{proto}://{host}:{port}'.format(proto=self.protocol, host=self.hostname,
                                               port=self.port)

        token = 'Bearer {token}'.format(token=self.token)
        config = ociclient.Configuration()
        config.host = url
        config.verify_ssl = self.verify_ssl
        config.debug = self.debug
        config.api_key['authorization'] = token

        self.ociclient = ociclient
        self.kclient = kubeclient
        self.oapi_client = ociclient.ApiClient(config=config)
        self.kapi_client = kubeclient.ApiClient(config=config)
        self.o_api = ociclient.OapiApi(api_client=self.oapi_client)
        self.k_api = kubeclient.CoreV1Api(api_client=self.kapi_client)
        self.security_api = self.ociclient.SecurityOpenshiftIoV1Api(api_client=self.oapi_client)
        self.batch_api = self.kclient.BatchV1Api(api_client=self.kapi_client)  # for job api 
Example #9
Source File: test_utils.py    From python with Apache License 2.0 6 votes vote down vote up
def test_create_implicit_service_list_from_yaml_with_conflict(self):
        """
        Should be able to create two services from a kind: ServiceList
        json file that implicitly indicates the kind of individual objects
        """
        k8s_client = client.api_client.ApiClient(configuration=self.config)
        with self.assertRaises(utils.FailToCreateError):
            utils.create_from_yaml(
                k8s_client, self.path_prefix + "implicit-svclist.json")
        core_api = client.CoreV1Api(k8s_client)
        svc_3 = core_api.read_namespaced_service(name="mock-3",
                                                 namespace="default")
        self.assertIsNotNone(svc_3)
        svc_4 = core_api.read_namespaced_service(name="mock-4",
                                                 namespace="default")
        self.assertIsNotNone(svc_4)
        core_api.delete_namespaced_service(name="mock-3",
                                           namespace="default", body={})
        core_api.delete_namespaced_service(name="mock-4",
                                           namespace="default", body={})

    # Tests for multi-resource yaml objects 
Example #10
Source File: test_utils.py    From python with Apache License 2.0 6 votes vote down vote up
def test_create_apps_deployment_from_yaml(self):
        """
        Should be able to create an apps/v1 deployment.
        """
        k8s_client = client.api_client.ApiClient(configuration=self.config)
        utils.create_from_yaml(
            k8s_client, self.path_prefix + "apps-deployment.yaml")
        app_api = client.AppsV1Api(k8s_client)
        dep = app_api.read_namespaced_deployment(name="nginx-app",
                                                 namespace="default")
        self.assertIsNotNone(dep)
        while True:
            try:
                app_api.delete_namespaced_deployment(
                    name="nginx-app", namespace="default",
                    body={})
                break
            except ApiException:
                continue 
Example #11
Source File: conftest.py    From inference-model-manager with Apache License 2.0 6 votes vote down vote up
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 #12
Source File: deployment_crud.py    From python with Apache License 2.0 6 votes vote down vote up
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 #13
Source File: kubeapi.py    From kqueen with MIT License 6 votes vote down vote up
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 #14
Source File: k8s.py    From armada with Apache License 2.0 6 votes vote down vote up
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 #15
Source File: test_utils.py    From python with Apache License 2.0 6 votes vote down vote up
def test_create_namespaced_apps_deployment_from_yaml(self):
        """
        Should be able to create an apps/v1beta1 deployment
		in a test namespace.
        """
        k8s_client = client.api_client.ApiClient(configuration=self.config)
        utils.create_from_yaml(
            k8s_client, self.path_prefix + "apps-deployment.yaml",
            namespace=self.test_namespace)
        app_api = client.AppsV1Api(k8s_client)
        dep = app_api.read_namespaced_deployment(name="nginx-app",
                                                 namespace=self.test_namespace)
        self.assertIsNotNone(dep)
        app_api.delete_namespaced_deployment(
            name="nginx-app", namespace=self.test_namespace,
            body={}) 
Example #16
Source File: k8s.py    From CPU-Manager-for-Kubernetes with Apache License 2.0 5 votes vote down vote up
def admissionregistartion_api_client_from_config(config):
    if config is None:
        k8sconfig.load_incluster_config()
        return k8sclient.AdmissionregistrationV1beta1Api()
    else:
        client = k8sclient.ApiClient(configuration=config)
        return k8sclient.AdmissionregistrationV1beta1Api(api_client=client) 
Example #17
Source File: kubewatch.py    From ambassador with Apache License 2.0 5 votes vote down vote up
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 #18
Source File: test_e2e.py    From illuminatio with Apache License 2.0 5 votes vote down vote up
def api_client(load_kube_config):
    return client.ApiClient() 
Example #19
Source File: k8s.py    From CPU-Manager-for-Kubernetes with Apache License 2.0 5 votes vote down vote up
def version_api_client_from_config(config):
    if config is None:
        k8sconfig.load_incluster_config()
        return k8sclient.VersionApi()
    else:
        client = k8sclient.ApiClient(configuration=config)
        return k8sclient.VersionApi(api_client=client) 
Example #20
Source File: k8s.py    From CPU-Manager-for-Kubernetes with Apache License 2.0 5 votes vote down vote up
def extensions_client_from_config(config):
    if config is None:
        k8sconfig.load_incluster_config()
        return k8sclient.ExtensionsV1beta1Api()
    else:
        client = k8sclient.ApiClient(configuration=config)
        return k8sclient.ExtensionsV1beta1Api(api_client=client) 
Example #21
Source File: k8s.py    From CPU-Manager-for-Kubernetes with Apache License 2.0 5 votes vote down vote up
def apps_api_client_from_config(config):
    if config is None:
        k8sconfig.load_incluster_config()
        return k8sclient.AppsV1Api()
    else:
        client = k8sclient.ApiClient(configuration=config)
        return k8sclient.AppsV1Api(api_client=client) 
Example #22
Source File: k8s.py    From CPU-Manager-for-Kubernetes with Apache License 2.0 5 votes vote down vote up
def client_from_config(config):
    if config is None:
        k8sconfig.load_incluster_config()
        return k8sclient.CoreV1Api()
    else:
        client = k8sclient.ApiClient(configuration=config)
        return k8sclient.CoreV1Api(api_client=client) 
Example #23
Source File: kubewatch.py    From ambassador with Apache License 2.0 5 votes vote down vote up
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 #24
Source File: kubewatch.py    From ambassador with Apache License 2.0 5 votes vote down vote up
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 #25
Source File: kubernetes_resources.py    From inference-model-manager with Apache License 2.0 5 votes vote down vote up
def get_k8s_extensions_api_client():
    apps_api_client = client.ExtensionsV1beta1Api(client.ApiClient(get_k8s_configuration()))
    return apps_api_client 
Example #26
Source File: ecrupdater.py    From ecr-updater with MIT License 5 votes vote down vote up
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 #27
Source File: KubernetesService.py    From k8s-mongo-operator with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self):
        # Create Kubernetes config.
        load_incluster_config()
        config = Configuration()
        config.debug = Settings.KUBERNETES_SERVICE_DEBUG
        self.api_client = client.ApiClient(config)

        # Re-usable API client instances.
        self.core_api = client.CoreV1Api(self.api_client)
        self.custom_objects_api = client.CustomObjectsApi(self.api_client)
        self.extensions_api = client.ApiextensionsV1beta1Api(self.api_client)
        self.apps_api = client.AppsV1beta1Api(self.api_client) 
Example #28
Source File: core.py    From seal with MIT License 5 votes vote down vote up
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 #29
Source File: kube_config.py    From ops-cli with Apache License 2.0 5 votes vote down vote up
def new_client_from_config(
        config_file=None,
        context=None,
        persist_config=True):
    """Loads configuration the same as load_kube_config but returns an ApiClient
    to be used with any API object. This will allow the caller to concurrently
    talk with multiple clusters."""
    client_config = type.__call__(Configuration)
    load_kube_config(config_file=config_file, context=context,
                     client_configuration=client_config,
                     persist_config=persist_config)
    return ApiClient(configuration=client_config) 
Example #30
Source File: watch.py    From python-base with Apache License 2.0 5 votes vote down vote up
def __init__(self, return_type=None):
        self._raw_return_type = return_type
        self._stop = False
        self._api_client = client.ApiClient()
        self.resource_version = None