Beispiel #1
0
async def load_kube_config(config_file=None,
                           context=None,
                           client_configuration=None,
                           persist_config=True):
    """Loads authentication and cluster information from kube-config file
    and stores them in kubernetes.client.configuration.

    :param config_file: Name of the kube-config file.
    :param context: set the active context. If is set to None, current_context
        from config file will be used.
    :param client_configuration: The kubernetes.client.Configuration to
        set configs to.
    :param persist_config: If True, config file will be updated when changed
        (e.g GCP token refresh).
    """

    if config_file is None:
        config_file = KUBE_CONFIG_DEFAULT_LOCATION

    loader = _get_kube_config_loader_for_yaml_file(
        config_file, active_context=context, persist_config=persist_config)
    if client_configuration is None:
        config = type.__call__(Configuration)
        await loader.load_and_set(config)
        Configuration.set_default(config)
    else:
        await loader.load_and_set(client_configuration)

    return loader
Beispiel #2
0
async def load_kube_config_from_dict(config_dict,
                                     context=None,
                                     client_configuration=None,
                                     temp_file_path=None):
    """Loads authentication and cluster information from config_dict
    and stores them in kubernetes.client.configuration.

    :param config_dict: Takes the config file as a dict.
    :param context: set the active context. If is set to None, current_context
        from config file will be used.
    :param client_configuration: The kubernetes_asyncio.client.Configuration to
        set configs to.
    :param temp_file_path: directory where temp files are stored
        (default - system temp dir).
    """

    loader = KubeConfigLoader(config_dict=config_dict,
                              config_base_path=None,
                              active_context=context,
                              temp_file_path=temp_file_path)

    if client_configuration is None:
        config = type.__call__(Configuration)
        await loader.load_and_set(config)
        Configuration.set_default(config)
    else:
        await loader.load_and_set(client_configuration)

    return loader
Beispiel #3
0
    async def load_kube_config(self):
        # Create a config loader, this will automatically refresh our credentials before they expire
        loader = self.get_kube_config_loader_for_yaml_file()

        # Grab our async + callback aware configuration
        config = AutoRefreshConfiguration(loader)

        await loader.load_and_set(config)
        Configuration.set_default(config)
Beispiel #4
0
async def refresh_token(loader, client_configuration=None, interval=60):
    """Refresh token if necessary, updates the token in client configurarion

    :param loader: KubeConfigLoader returned by load_kube_config
    :param client_configuration: The kubernetes.client.Configuration to
            set configs to.
    :param interval: how often check if token is up-to-date

    """
    if loader.provider != 'gcp':
        return

    if client_configuration is None:
        client_configuration = Configuration()

    while 1:
        await asyncio.sleep(interval)
        await loader.load_gcp_token()
        client_configuration.api_key['authorization'] = loader.token
async def login_via_kubernetes_asyncio(
    logger: Union[logging.Logger, logging.LoggerAdapter],
    **kwargs: Any,
) -> ConnectionInfo:
    """
    Authenticate with the Kubernetes cluster.

    Upon startup of the Kopf operator, this function attempts to authenticate
    with a Kubernetes cluster. If the
    :attr:`~crate.operator.config.Config.KUBECONFIG` is defined, an attempt
    will be made to use that config file. In other cases, an in-cluster
    authentication will be tried.
    """
    if config.KUBECONFIG:
        logger.info("Authenticating with KUBECONFIG='%s'", config.KUBECONFIG)
        await load_kube_config(config_file=config.KUBECONFIG)
    else:
        logger.info("Authenticating with in-cluster config")
        load_incluster_config()

    # Below follows a copy of Kopf's `kopf.utilities.piggybacking.login_via_client`

    # We do not even try to understand how it works and why. Just load it, and
    # extract the results.
    k8s_config = Configuration.get_default_copy()

    # For auth-providers, this method is monkey-patched with the
    # auth-provider's one.
    # We need the actual auth-provider's token, so we call it instead of
    # accessing api_key.
    # Other keys (token, tokenFile) also end up being retrieved via this method.
    header: Optional[str] = k8s_config.get_api_key_with_prefix("authorization")
    parts: Sequence[str] = header.split(" ", 1) if header else []
    scheme, token = ((None, None) if len(parts) == 0 else
                     (None, parts[0]) if len(parts) == 1 else
                     (parts[0], parts[1]))  # RFC-7235, Appendix C.

    # Interpret the k8s_config object for our own minimalistic credentials.
    # Note: kubernetes client has no concept of a "current" context's namespace.
    c = ConnectionInfo(
        server=k8s_config.host,
        ca_path=k8s_config.ssl_ca_cert,  # can be a temporary file
        insecure=not k8s_config.verify_ssl,
        username=k8s_config.username
        or None,  # an empty string when not defined
        password=k8s_config.password
        or None,  # an empty string when not defined
        scheme=scheme,
        token=token,
        certificate_path=k8s_config.cert_file,  # can be a temporary file
        private_key_path=k8s_config.key_file,  # can be a temporary file
        priority=
        30,  # The priorities for `client` and `pykube-ng` are 10 and 20.
    )
    return c
async def load_kube_config(config_file=None,
                           context=None,
                           client_configuration=None,
                           persist_config=True):
    """Loads authentication and cluster information from kube-config file
    and stores them in kubernetes.client.configuration.

    :param config_file: Name of the kube-config file.
    :param context: set the active context. If is set to None, current_context
        from config file will be used.
    :param client_configuration: The kubernetes.client.Configuration to
        set configs to.
    :param persist_config: If True, config file will be updated when changed
        (e.g GCP token refresh).
    """

    if config_file is None:
        config_file = os.path.expanduser(KUBE_CONFIG_DEFAULT_LOCATION)

    config_persister = None
    if persist_config:

        def _save_kube_config(config_map):
            with open(config_file, 'w') as f:
                yaml.safe_dump(config_map, f, default_flow_style=False)

        config_persister = _save_kube_config

    loader = _get_kube_config_loader_for_yaml_file(
        config_file, active_context=context, config_persister=config_persister)
    if client_configuration is None:
        config = type.__call__(Configuration)
        await loader.load_and_set(config)
        Configuration.set_default(config)
    else:
        await loader.load_and_set(client_configuration)

    return loader
Beispiel #7
0
 def _set_config(self):
     configuration = Configuration()
     configuration.host = self.host
     configuration.ssl_ca_cert = self.ssl_ca_cert
     configuration.api_key['authorization'] = "bearer " + self.token
     Configuration.set_default(configuration)