Beispiel #1
0
    def __init__(self, *, path: fs.FilePath = None, data: str = None) -> None:
        """
        :param path: Path to a file containing the data.
        :param data: Data encoded in Base64.
        """
        self._path: Optional[Path] = None
        self._bytes: Optional[bytes] = None
        self._temporary_file = None

        if path is not None and data is not None:
            raise TypeError("'path' or 'data' must be specified, but not both")
        if path is not None:
            path = Path(path)
            if not path.is_file():
                raise errors.PyKubeError(f"{path} is not a regular file")
            self._path = path
            self._origin_format = DataFormat.PATH
        elif data is not None:
            try:
                self._bytes = base64.b64decode(data, validate=True)
            except binascii.Error as err:
                raise errors.PyKubeError(
                    "failed to decode base64 value") from err
            self._origin_format = DataFormat.BASE64
        else:
            raise TypeError("one of 'path' or 'data' kwargs must be specified")
Beispiel #2
0
    def current_context(self, context: str) -> None:
        """
        Set the current context.
        It will not be persisted in the original data source from which this
        KubeConfig instance has been created.

        https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/#context

        :raise exceptions.PyKubeError: If the provided context name is invalid.
        """
        if not context:
            raise errors.PyKubeError(f"invalid context: {context!r}")

        if context not in self.contexts:
            joined = ", ".join(repr(name) for name in self.contexts)
            raise errors.PyKubeError(
                f"unknown context {context!r}; choose among {joined}")

        self._current_context = context
Beispiel #3
0
    def current_context(self) -> str:
        """
        The current context defined in the configuration, if any.

        https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/#context

        :raise exceptions.PyKubeError: If no current context is set.
        """
        if self._current_context is None:
            raise errors.PyKubeError("current context not set")
        return self._current_context
Beispiel #4
0
    async def from_service_account(
        cls,
        path: fs.FilePath = "/var/run/secrets/kubernetes.io/serviceaccount"
    ) -> "KubeConfig":
        """
        Builds a KubeConfig instance from the kubeconfig of an in-cluster
        service account.

        :raise exceptions.PyKubeError: If neither PYKUBE_KUBERNETES_SERVICE_HOST
            nor KUBERNETES_SERVICE_HOST, or neither PYKUBE_KUBERNETES_SERVICE_PORT
            nor KUBERNETES_SERVICE_PORT, is available as environment variable.
        """
        try:
            host, port = [
                os.getenv(
                    f"PYKUBE_KUBERNETES_SERVICE_{k}",
                    os.environ[f"KUBERNETES_SERVICE_{k}"],
                ) for k in ("HOST", "PORT")
            ]
        except KeyError as err:
            raise errors.PyKubeError(f"missing env variable: {err}") from None

        token = await fs.read_text(Path(path, "token"))
        doc = {
            "clusters": [{
                "name": "self",
                "cluster": {
                    "server": f"https://{host}:{port}",
                    "certificate-authority": str(Path(path, "ca.crt")),
                },
            }],
            "users": [{
                "name": "self",
                "user": {
                    "token": token
                }
            }],
            "contexts": [{
                "name": "self",
                "context": {
                    "cluster": "self",
                    "user": "******"
                }
            }],
            "current-context":
            "self",
        }
        return cls(doc)
Beispiel #5
0
    async def from_file(cls,
                        path: Optional[fs.FilePath] = None) -> "KubeConfig":
        """
        Builds a KubeConfig instance from a kubeconfig file.

        Later updates to that file are not reflected in this instance.
        Similarly, updates to this instance are not written to this file,
        except via :meth:`persist`.

        :param path: Full path to a kubeconfig file. If None, defaults to the
            value of the KUBECONFIG environment variable. If that variable is
            undefined, defaults to ``$HOME/.kube/config``.
        """
        if path is None:
            path = os.getenv("KUBECONFIG",
                             Path.home().joinpath(".kube", "config"))
        path = Path(path)
        try:
            doc = yaml.safe_load(await fs.read_text(path))
        except (OSError, yaml.YAMLError) as err:
            raise errors.PyKubeError(
                f"couldn't load kubeconfig file {path}") from err
        return cls(doc, path=path)