Path: blob/main/install/installer/cmd/config_cluster.go
2498 views
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.1/// Licensed under the GNU Affero General Public License (AGPL).2// See License.AGPL.txt in the project root for license information.34package cmd56import (7"context"8"path/filepath"910"github.com/gitpod-io/gitpod/common-go/log"11"github.com/spf13/cobra"12v1 "k8s.io/api/core/v1"13"k8s.io/apimachinery/pkg/api/errors"14metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"15"k8s.io/client-go/kubernetes"16"k8s.io/client-go/rest"17"k8s.io/client-go/tools/clientcmd"18"k8s.io/client-go/util/homedir"19)2021var configClusterOpts struct {22Kube kubeConfig23Namespace string24EnsureNamespace bool25}2627// configClusterCmd represents the validate command28var configClusterCmd = &cobra.Command{29Use: "cluster",30Short: "Perform configuration tasks against the cluster",31Long: `Perform configuration tasks against the cluster3233These will be deployed and run as Kubernetes resources.`,34PersistentPreRunE: func(cmd *cobra.Command, args []string) error {35log.Debugf("EnsureNamespace: %t", configClusterOpts.EnsureNamespace)3637if !configClusterOpts.EnsureNamespace {38return nil39}4041log.Infof("Ensuring namespace exists %s", configClusterOpts.Namespace)42_, clientset, err := authClusterOrKubeconfig(configClusterOpts.Kube.Config)43if err != nil {44return err45}4647_, err = clientset.CoreV1().Namespaces().Create(48context.TODO(),49&v1.Namespace{50ObjectMeta: metav1.ObjectMeta{51Name: configClusterOpts.Namespace,52},53},54metav1.CreateOptions{},55)5657if errors.IsAlreadyExists(err) {58log.Debug("Namespace already exists")59return nil60}6162return err63},64}6566func init() {67configCmd.AddCommand(configClusterCmd)6869configClusterCmd.Flags().StringVar(&configClusterOpts.Kube.Config, "kubeconfig", filepath.Join(homedir.HomeDir(), ".kube", "config"), "path to the kubeconfig file")70configClusterCmd.PersistentFlags().StringVarP(&configClusterOpts.Namespace, "namespace", "n", getEnvvar("NAMESPACE", "default"), "namespace to deploy to")71configClusterCmd.PersistentFlags().BoolVar(&configClusterOpts.EnsureNamespace, "ensure-namespace", true, "ensure that the namespace exists")72}7374func authClusterOrKubeconfig(kubeconfig string) (*rest.Config, *kubernetes.Clientset, error) {75// Try authenticating in-cluster with serviceaccount76log.Debug("Attempting to authenticate with ServiceAccount")77config, err := rest.InClusterConfig()78if err != nil {79// Try authenticating out-of-cluster with kubeconfig80log.Debug("ServiceAccount failed - using KubeConfig")81config, err = clientcmd.BuildConfigFromFlags("", kubeconfig)82if err != nil {83return nil, nil, err84}85}8687clientset, err := kubernetes.NewForConfig(config)88if err != nil {89return nil, nil, err90}9192return config, clientset, nil93}949596