示例#1
0
    def login_to_kubernetes_cluster(self, cluster_name: str) -> None:
        """Login the kubectl CLI to AKS cluster described in the cluster configuration"""
        self.logger.info("Logging in kubernetes CLI client to cluster")

        run_shell_command([
            "az",
            "aks",
            "get-credentials",
            "--resource-group",
            self.rsg,
            "--name",
            cluster_name,
            "--overwrite-existing",
        ])
示例#2
0
    def copy_secret(self, name: str, from_namespace: str) -> None:
        """Copy Kubernetes secret from another namespace

        Args:
            name (str): name of the secret
            from_namespace (str): where to copy the secret from
        """
        run_shell_command(
            f"kubectl get secret {name} --namespace={from_namespace} -oyaml | "
            f"sed -e 's@namespaces/{from_namespace}@namespaces/{self.namespace}@' | "
            f"sed -e 's@namespace: {from_namespace}@namespace: \"{self.namespace}\"@' | "
            f"kubectl apply --namespace={self.namespace} -f -",
            shell=True,
        )
示例#3
0
    def exists(self, name: str) -> bool:
        """Check if HELM chart exists in namespace on cluster

        Args:
            name (str): name of the HELM chart

        Returns:
            bool: whether chart is installed
        """
        try:
            run_shell_command(["helm", "status", name] + self.namespace_args)
            return True
        except RuntimeError:
            return False
示例#4
0
    def uninstall(self, name: str, tolerate_error=False) -> None:
        """Uninstall HELM chart from cluster

        Args:
            name (str): name of the chart
            tolerate_error (bool, optional): if true, errors are tolerated. Defaults to False.

        Raises:
            RuntimeError: If error is not tolerated and something goes wrong
        """
        try:
            run_shell_command(["helm", "uninstall", name] +
                              self.namespace_args)
        except RuntimeError as e:
            if not tolerate_error:
                raise e
示例#5
0
    def install(
        self,
        name: str,
        chart: Union[str, Path],
        config_map: dict,
        reinstall: bool = True,
        atomic: bool = True,
        timeout: str = "900s",
        extra_args: List[str] = [],
    ) -> None:
        """Install a Helm chart

        Args:
            name (str): name of the chart
            chart (Union[str, Path]): Path to the chart
            config_map (dict): dictionary of key-value pairs for the chart values
            reinstall (bool, optional): whether to uninstall the chart first. Defaults to True.
            atomic (bool, optional): atomic - so wait for the results. Defaults to True.
            timeout (str, optional): timeout for the installation. Defaults to "900s".
            extra_args (List, optional): extra HELM argument list. Defaults to [].
        """
        if reinstall:
            self.uninstall(name, tolerate_error=True)

        values = [f"{key}={value}" for key, value in config_map.items()]
        args = []
        for v in values:
            args.append("--set")
            args.append(v)

        if atomic:
            args.append("--atomic")
        args.append(f"--timeout={timeout}")
        args.append("--debug")

        helm_cmd = "install"
        if not reinstall and self.exists(name):
            helm_cmd = "upgrade"

        cmd = ["helm", helm_cmd, name, str(chart)
               ] + self.namespace_args + args + extra_args

        run_shell_command(cmd)
示例#6
0
def get_latest_version_on_azure(location: str) -> str:
    """Get latest available AKS cluster version

    Args:
        location (str): name of the Azure location

    Returns:
        str: latest version
    """
    out, _ = run_shell_command(
        ["az", "aks", "get-versions", "-l", location, "-o", "json"])
    versions = json.loads(out)["orchestrators"]
    stable = [i["orchestratorVersion"] for i in versions if not i["isPreview"]]
    stable.sort()
    return stable[-1]
示例#7
0
    def add_repo(self, branch: str, name: str) -> None:
        """Add and update repo from public repos

        Args:
            branch (str): branch name for the repo
            name (str): repo name
        """
        if name not in repos:
            run_shell_command(["helm", "repo", "add", branch, name])
            repos.append(name)

            retries = 10
            i = 0
            while True:
                try:
                    run_shell_command(["helm", "repo", "update"])
                except:
                    logging.error("Could not update HELM repo!")
                    i += 1
                else:
                    break

                if i == retries:
                    raise RuntimeError("Cannot update HELM repo!!")
示例#8
0
    def kube_cmd(self,
                 args: List[str],
                 namespaced: bool = True) -> Tuple[str, str]:
        """Run a kubectl command with given arguments in a given namespace

        Args:
            args (list): kubectl command arguments in order
            namespaced (bool, optional): whether to run it in cluster level or namespaced. Defaults to True.

        Returns:
            Tuple[str, str]: output, error of the run shell command
        """
        namespace_args = [] if not namespaced else [
            "--namespace", self.namespace
        ]
        wait_args = [] if args[0] in [
            "create", "get", "rollout", "label", "scale", "logs"
        ] else self.wait_args

        return run_shell_command(["kubectl"] + args + namespace_args +
                                 wait_args,
                                 poll=False)