Skip to content

prefect_kubernetes.credentials

Module for defining Kubernetes credential handling and client generation.

Classes

KubernetesCredentials

Bases: Block

Credentials block for generating configured Kubernetes API clients.

Attributes:

Name Type Description
cluster_config Optional[KubernetesClusterConfig]

A KubernetesClusterConfig block holding a JSON kube config for a specific kubernetes context.

Example

Load stored Kubernetes credentials:

from prefect_kubernetes.credentials import KubernetesCredentials

kubernetes_credentials = KubernetesCredentials.load("BLOCK_NAME")

Source code in prefect_kubernetes/credentials.py
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
class KubernetesCredentials(Block):
    """Credentials block for generating configured Kubernetes API clients.

    Attributes:
        cluster_config: A `KubernetesClusterConfig` block holding a JSON kube
            config for a specific kubernetes context.

    Example:
        Load stored Kubernetes credentials:
        ```python
        from prefect_kubernetes.credentials import KubernetesCredentials

        kubernetes_credentials = KubernetesCredentials.load("BLOCK_NAME")
        ```
    """

    _block_type_name = "Kubernetes Credentials"
    _logo_url = "https://images.ctfassets.net/zscdif0zqppk/oYuHjIbc26oilfQSEMjRv/a61f5f6ef406eead2df5231835b4c4c2/logo.png?h=250"  # noqa
    _documentation_url = "https://prefecthq.github.io/prefect-kubernetes/credentials/#prefect_kubernetes.credentials.KubernetesCredentials"  # noqa

    cluster_config: Optional[KubernetesClusterConfig] = None

    @contextmanager
    def get_client(
        self,
        client_type: Literal["apps", "batch", "core", "custom_objects"],
        configuration: Optional[Configuration] = None,
    ) -> Generator[KubernetesClient, None, None]:
        """Convenience method for retrieving a Kubernetes API client for deployment resources.

        Args:
            client_type: The resource-specific type of Kubernetes client to retrieve.

        Yields:
            An authenticated, resource-specific Kubernetes API client.

        Example:
            ```python
            from prefect_kubernetes.credentials import KubernetesCredentials

            with KubernetesCredentials.get_client("core") as core_v1_client:
                for pod in core_v1_client.list_namespaced_pod():
                    print(pod.metadata.name)
            ```
        """
        client_config = configuration or Configuration()

        with ApiClient(configuration=client_config) as generic_client:
            try:
                yield self.get_resource_specific_client(client_type)
            finally:
                generic_client.rest_client.pool_manager.clear()

    def get_resource_specific_client(
        self,
        client_type: str,
    ) -> Union[AppsV1Api, BatchV1Api, CoreV1Api]:
        """
        Utility function for configuring a generic Kubernetes client.
        It will attempt to connect to a Kubernetes cluster in three steps with
        the first successful connection attempt becoming the mode of communication with
        a cluster:

        1. It will first attempt to use a `KubernetesCredentials` block's
        `cluster_config` to configure a client using
        `KubernetesClusterConfig.configure_client`.

        2. Attempt in-cluster connection (will only work when running on a pod).

        3. Attempt out-of-cluster connection using the default location for a
        kube config file.

        Args:
            client_type: The Kubernetes API client type for interacting with specific
                Kubernetes resources.

        Returns:
            KubernetesClient: An authenticated, resource-specific Kubernetes Client.

        Raises:
            ValueError: If `client_type` is not a valid Kubernetes API client type.
        """

        if self.cluster_config:
            self.cluster_config.configure_client()
        else:
            try:
                kube_config.load_incluster_config()
            except ConfigException:
                kube_config.load_kube_config()

        try:
            return K8S_CLIENT_TYPES[client_type]()
        except KeyError:
            raise ValueError(
                f"Invalid client type provided '{client_type}'."
                f" Must be one of {listrepr(K8S_CLIENT_TYPES.keys())}."
            )

Functions

get_client

Convenience method for retrieving a Kubernetes API client for deployment resources.

Parameters:

Name Type Description Default
client_type Literal['apps', 'batch', 'core', 'custom_objects']

The resource-specific type of Kubernetes client to retrieve.

required

Yields:

Type Description
KubernetesClient

An authenticated, resource-specific Kubernetes API client.

Example
from prefect_kubernetes.credentials import KubernetesCredentials

with KubernetesCredentials.get_client("core") as core_v1_client:
    for pod in core_v1_client.list_namespaced_pod():
        print(pod.metadata.name)
Source code in prefect_kubernetes/credentials.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
@contextmanager
def get_client(
    self,
    client_type: Literal["apps", "batch", "core", "custom_objects"],
    configuration: Optional[Configuration] = None,
) -> Generator[KubernetesClient, None, None]:
    """Convenience method for retrieving a Kubernetes API client for deployment resources.

    Args:
        client_type: The resource-specific type of Kubernetes client to retrieve.

    Yields:
        An authenticated, resource-specific Kubernetes API client.

    Example:
        ```python
        from prefect_kubernetes.credentials import KubernetesCredentials

        with KubernetesCredentials.get_client("core") as core_v1_client:
            for pod in core_v1_client.list_namespaced_pod():
                print(pod.metadata.name)
        ```
    """
    client_config = configuration or Configuration()

    with ApiClient(configuration=client_config) as generic_client:
        try:
            yield self.get_resource_specific_client(client_type)
        finally:
            generic_client.rest_client.pool_manager.clear()
get_resource_specific_client

Utility function for configuring a generic Kubernetes client. It will attempt to connect to a Kubernetes cluster in three steps with the first successful connection attempt becoming the mode of communication with a cluster:

  1. It will first attempt to use a KubernetesCredentials block's cluster_config to configure a client using KubernetesClusterConfig.configure_client.

  2. Attempt in-cluster connection (will only work when running on a pod).

  3. Attempt out-of-cluster connection using the default location for a kube config file.

Parameters:

Name Type Description Default
client_type str

The Kubernetes API client type for interacting with specific Kubernetes resources.

required

Returns:

Name Type Description
KubernetesClient Union[AppsV1Api, BatchV1Api, CoreV1Api]

An authenticated, resource-specific Kubernetes Client.

Raises:

Type Description
ValueError

If client_type is not a valid Kubernetes API client type.

Source code in prefect_kubernetes/credentials.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def get_resource_specific_client(
    self,
    client_type: str,
) -> Union[AppsV1Api, BatchV1Api, CoreV1Api]:
    """
    Utility function for configuring a generic Kubernetes client.
    It will attempt to connect to a Kubernetes cluster in three steps with
    the first successful connection attempt becoming the mode of communication with
    a cluster:

    1. It will first attempt to use a `KubernetesCredentials` block's
    `cluster_config` to configure a client using
    `KubernetesClusterConfig.configure_client`.

    2. Attempt in-cluster connection (will only work when running on a pod).

    3. Attempt out-of-cluster connection using the default location for a
    kube config file.

    Args:
        client_type: The Kubernetes API client type for interacting with specific
            Kubernetes resources.

    Returns:
        KubernetesClient: An authenticated, resource-specific Kubernetes Client.

    Raises:
        ValueError: If `client_type` is not a valid Kubernetes API client type.
    """

    if self.cluster_config:
        self.cluster_config.configure_client()
    else:
        try:
            kube_config.load_incluster_config()
        except ConfigException:
            kube_config.load_kube_config()

    try:
        return K8S_CLIENT_TYPES[client_type]()
    except KeyError:
        raise ValueError(
            f"Invalid client type provided '{client_type}'."
            f" Must be one of {listrepr(K8S_CLIENT_TYPES.keys())}."
        )