From 32fded17545f4459b071ab38c3c7d6acfe517f4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartal=20L=C3=A6arsson?= Date: Sat, 1 Mar 2025 23:46:45 +0000 Subject: [PATCH] add go cli initial --- .gitignore | 19 ++ cli/README.md | 96 +++++++++ cli/cmd/provision/ansible/playbook.go | 36 ++++ cli/cmd/provision/cmd/cleanup.go | 48 +++++ cli/cmd/provision/cmd/provision.go | 36 ++++ cli/cmd/provision/cmd/root.go | 32 +++ cli/cmd/provision/interactive/prompt.go | 147 +++++++++++++ cli/cmd/provision/kubernetes/provision.go | 243 ++++++++++++++++++++++ cli/cmd/provision/main.go | 15 ++ cli/cmd/provision/postgres/provision.go | 0 cli/go.mod | 21 ++ cli/go.sum | 58 ++++++ cli/install.sh | 65 ++++++ cli/scripts/build-release.sh | 76 +++++++ 14 files changed, 892 insertions(+) create mode 100644 cli/README.md create mode 100644 cli/cmd/provision/ansible/playbook.go create mode 100644 cli/cmd/provision/cmd/cleanup.go create mode 100644 cli/cmd/provision/cmd/provision.go create mode 100644 cli/cmd/provision/cmd/root.go create mode 100644 cli/cmd/provision/interactive/prompt.go create mode 100644 cli/cmd/provision/kubernetes/provision.go create mode 100644 cli/cmd/provision/main.go create mode 100644 cli/cmd/provision/postgres/provision.go create mode 100644 cli/go.mod create mode 100644 cli/go.sum create mode 100644 cli/install.sh create mode 100755 cli/scripts/build-release.sh diff --git a/.gitignore b/.gitignore index dd039bc..766a94e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,22 @@ multipass/cloud-init/ssh_key.txt multipass/cloud-init/common_processed.yaml ansible/inventories/kubernetes.yml + + +# Go build artifacts (except for released binaries) +/build/ +/bin/ +# Uncomment the lines above if you don't want to include binaries in the repo + +# Go dependency directories +/vendor/ + +# Go test cache +*.test +*.out + +# IDE files +.idea/ +.vscode/ +*.swp +*.swo diff --git a/cli/README.md b/cli/README.md new file mode 100644 index 0000000..9637456 --- /dev/null +++ b/cli/README.md @@ -0,0 +1,96 @@ +# Infrastructure CLI Tool + +A simple interactive CLI tool for managing infrastructure provisioning and cleanup. This tool replaces the existing scripts with a more user-friendly interface while maintaining compatibility with the Ansible playbooks. + +## Installation + +### Option 1: Quick Install (Linux/macOS) + +Run the installation script: + +```bash +./install.sh +``` + +This will install the CLI tool to `~/.local/bin` and provide instructions if you need to update your PATH. + +### Option 2: Manual Install + +1. Find the appropriate binary for your platform in the `bin` directory: + - Linux/AMD64: `bin/linux_amd64/provision` + - Linux/ARM64: `bin/linux_arm64/provision` + - macOS/AMD64: `bin/darwin_amd64/provision` + - macOS/ARM64: `bin/darwin_arm64/provision` + - Windows: `bin/windows_amd64/provision.exe` + +2. Copy it to a location in your PATH: + ```bash + # Example for Linux/macOS + cp bin/linux_amd64/provision ~/.local/bin/ + chmod +x ~/.local/bin/provision + ``` + +## Usage + +Simply run the command to start the interactive CLI: + +```bash +provision +``` + +You'll be guided through a series of prompts to: + +1. Choose an operation (provision or cleanup) +2. Select what to provision/cleanup (Kubernetes or PostgreSQL) +3. Configure settings or use defaults +4. Confirm and execute the operation + +### Example: Provisioning Kubernetes + +``` +$ provision + +? What would you like to do? provision +? What would you like to provision? Kubernetes Cluster + +Current default settings: +Kubernetes Version: 1.28 +Pod CIDR: 192.168.0.0/16 +Service CIDR: 10.96.0.0/16 +CNI Plugin: calico +Control Plane: 2 CPUs, 4G Memory, 20G Disk +Worker Nodes: 2 CPUs, 4G Memory, 20G Disk + +? Do you want to use these default settings? Yes +? Do you want to proceed? Yes + +Running provisioning script... +``` + +### Example: Cleaning Up + +``` +$ provision + +? What would you like to do? cleanup +? What would you like to clean up? Kubernetes Cluster +? Are you sure you want to clean up Kubernetes Cluster? Yes + +Starting Kubernetes cluster cleanup... +Cleanup completed successfully +``` + +## Requirements + +- Ansible (for provisioning operations) +- Multipass (for VM creation) + +## Developing the CLI Tool + +If you want to modify or extend the CLI tool: + +1. Make changes to the Go code in the `cmd/provision` directory +2. Run the build script to rebuild binaries: + ```bash + ./scripts/build-release.sh + ``` diff --git a/cli/cmd/provision/ansible/playbook.go b/cli/cmd/provision/ansible/playbook.go new file mode 100644 index 0000000..dd06c6b --- /dev/null +++ b/cli/cmd/provision/ansible/playbook.go @@ -0,0 +1,36 @@ +package ansible + +import ( + "fmt" + "os" + "os/exec" +) + +// RunPlaybook executes an Ansible playbook with the given inventory and extra variables +func RunPlaybook(playbook, inventory string, extraArgs []string) error { + // Check if ansible-playbook is available + if _, err := exec.LookPath("ansible-playbook"); err != nil { + return fmt.Errorf("ansible-playbook command not found: %w", err) + } + + // Build the command + args := []string{"-i", inventory} + + // Add any extra arguments + args = append(args, extraArgs...) + + // Add the playbook at the end + args = append(args, playbook) + + // Create the command + cmd := exec.Command("ansible-playbook", args...) + + // Connect the command's outputs to our process's outputs + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + cmd.Stdin = os.Stdin // Pass stdin for any prompts + + // Run the command + fmt.Printf("Running: ansible-playbook %v\n", args) + return cmd.Run() +} diff --git a/cli/cmd/provision/cmd/cleanup.go b/cli/cmd/provision/cmd/cleanup.go new file mode 100644 index 0000000..a8682de --- /dev/null +++ b/cli/cmd/provision/cmd/cleanup.go @@ -0,0 +1,48 @@ +package cmd + +import ( + "fmt" + + "github.com/bxtal-lsn/kubernetes/cli/cmd/provision/interactive" + "github.com/bxtal-lsn/kubernetes/cli/cmd/provision/kubernetes" + "github.com/spf13/cobra" +) + +var cleanupCmd = &cobra.Command{ + Use: "cleanup", + Short: "Clean up provisioned resources", + Long: `Clean up provisioned infrastructure components like Kubernetes clusters, PostgreSQL, etc.`, + Run: func(cmd *cobra.Command, args []string) { + cleanupInteractive() + }, +} + +func cleanupInteractive() { + options := []string{"Kubernetes Cluster", "PostgreSQL Cluster"} + choice, err := interactive.PromptSelect("What would you like to clean up?", options) + if err != nil { + exitWithError("Failed to get user input", err) + } + + confirmed, err := interactive.PromptConfirm(fmt.Sprintf("Are you sure you want to clean up %s?", choice)) + if err != nil { + exitWithError("Failed to get confirmation", err) + } + + if !confirmed { + fmt.Println("Cleanup cancelled") + return + } + + switch choice { + case "Kubernetes Cluster": + fmt.Println("Starting Kubernetes cluster cleanup...") + if err := kubernetes.Cleanup(); err != nil { + exitWithError("Failed to clean up Kubernetes cluster", err) + } + default: + fmt.Println("Invalid choice") + } + + fmt.Println("Cleanup completed successfully") +} diff --git a/cli/cmd/provision/cmd/provision.go b/cli/cmd/provision/cmd/provision.go new file mode 100644 index 0000000..2538a72 --- /dev/null +++ b/cli/cmd/provision/cmd/provision.go @@ -0,0 +1,36 @@ +package cmd + +import ( + "fmt" + + "github.com/bxtal-lsn/kubernetes/cli/cmd/provision/interactive" + "github.com/bxtal-lsn/kubernetes/cli/cmd/provision/kubernetes" + "github.com/spf13/cobra" +) + +var provisionCmd = &cobra.Command{ + Use: "provision", + Short: "Provision infrastructure components", + Long: `Provision infrastructure components like Kubernetes clusters, PostgreSQL, etc.`, + Run: func(cmd *cobra.Command, args []string) { + provisionInteractive() + }, +} + +func provisionInteractive() { + options := []string{"Kubernetes Cluster", "PostgreSQL Cluster"} + choice, err := interactive.PromptSelect("What would you like to provision?", options) + if err != nil { + exitWithError("Failed to get user input", err) + } + + switch choice { + case "Kubernetes Cluster": + fmt.Println("Starting Kubernetes cluster provisioning...") + if err := kubernetes.ProvisionInteractive(); err != nil { + exitWithError("Failed to provision Kubernetes cluster", err) + } + default: + fmt.Println("Invalid choice") + } +} diff --git a/cli/cmd/provision/cmd/root.go b/cli/cmd/provision/cmd/root.go new file mode 100644 index 0000000..1435e46 --- /dev/null +++ b/cli/cmd/provision/cmd/root.go @@ -0,0 +1,32 @@ +package cmd + +import ( + "fmt" + "os" + + "github.com/spf13/cobra" +) + +var rootCmd = &cobra.Command{ + Use: "provision", + Short: "Infrastructure provisioning tool", + Long: `A flexible CLI for provisioning and managing infrastructure components +such as Kubernetes clusters, PostgreSQL clusters, and more.`, +} + +// Execute adds all child commands to the root command and sets flags appropriately. +func Execute() error { + return rootCmd.Execute() +} + +func init() { + // Initialize commands + rootCmd.AddCommand(provisionCmd) + rootCmd.AddCommand(cleanupCmd) +} + +// Display an error message and exit +func exitWithError(msg string, err error) { + fmt.Fprintf(os.Stderr, "%s: %v\n", msg, err) + os.Exit(1) +} diff --git a/cli/cmd/provision/interactive/prompt.go b/cli/cmd/provision/interactive/prompt.go new file mode 100644 index 0000000..a052fbd --- /dev/null +++ b/cli/cmd/provision/interactive/prompt.go @@ -0,0 +1,147 @@ +package interactive + +import ( + "fmt" + "strconv" + "strings" + + "github.com/AlecAivazis/survey/v2" +) + +// PromptText asks the user for text input +func PromptText(message string, defaultValue string) (string, error) { + var result string + + prompt := &survey.Input{ + Message: message, + Default: defaultValue, + } + + err := survey.AskOne(prompt, &result) + return result, err +} + +// PromptPassword asks the user for a password input +func PromptPassword(message string) (string, error) { + var result string + + prompt := &survey.Password{ + Message: message, + } + + err := survey.AskOne(prompt, &result) + return result, err +} + +// PromptSelect asks the user to select from a list of options +func PromptSelect(message string, options []string) (string, error) { + var result string + + prompt := &survey.Select{ + Message: message, + Options: options, + } + + err := survey.AskOne(prompt, &result) + return result, err +} + +// PromptConfirm asks the user for confirmation (yes/no) +func PromptConfirm(message string) (bool, error) { + var result bool + + prompt := &survey.Confirm{ + Message: message, + } + + err := survey.AskOne(prompt, &result) + return result, err +} + +// PromptInt asks the user for an integer value +func PromptInt(message string, defaultValue int) (int, error) { + var result string + + prompt := &survey.Input{ + Message: message, + Default: strconv.Itoa(defaultValue), + } + + err := survey.AskOne(prompt, &result, survey.WithValidator(survey.Required)) + if err != nil { + return 0, err + } + + return strconv.Atoi(result) +} + +// PromptIntWithRange asks the user for an integer value within a range +func PromptIntWithRange(message string, defaultValue, min, max int) (int, error) { + for { + val, err := PromptInt(message, defaultValue) + if err != nil { + return 0, err + } + + if val < min || val > max { + fmt.Printf("Value must be between %d and %d\n", min, max) + continue + } + + return val, nil + } +} + +// PromptYamlVariables prompts the user for values for a set of YAML variables +func PromptYamlVariables(variables map[string]interface{}) (map[string]interface{}, error) { + result := make(map[string]interface{}) + + for key, defaultValue := range variables { + switch v := defaultValue.(type) { + case string: + val, err := PromptText(fmt.Sprintf("%s (%s)", key, v), v) + if err != nil { + return nil, err + } + result[key] = val + + case int: + val, err := PromptInt(fmt.Sprintf("%s (%d)", key, v), v) + if err != nil { + return nil, err + } + result[key] = val + + case bool: + val, err := PromptConfirm(fmt.Sprintf("%s (%t)", key, v)) + if err != nil { + return nil, err + } + result[key] = val + + case []string: + defaultStr := strings.Join(v, ", ") + val, err := PromptText(fmt.Sprintf("%s (%s)", key, defaultStr), defaultStr) + if err != nil { + return nil, err + } + + if val == defaultStr { + result[key] = v + } else { + parts := strings.Split(val, ",") + trimmed := make([]string, len(parts)) + for i, p := range parts { + trimmed[i] = strings.TrimSpace(p) + } + result[key] = trimmed + } + + default: + // For complex types or unsupported types, just use the default + result[key] = defaultValue + } + } + + return result, nil +} diff --git a/cli/cmd/provision/kubernetes/provision.go b/cli/cmd/provision/kubernetes/provision.go new file mode 100644 index 0000000..ee53f05 --- /dev/null +++ b/cli/cmd/provision/kubernetes/provision.go @@ -0,0 +1,243 @@ +package kubernetes + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + + "github.com/bxtal-lsn/kubernetes/cli/cmd/provision/ansible" + "github.com/bxtal-lsn/kubernetes/cli/cmd/provision/interactive" + "gopkg.in/yaml.v3" +) + +// Config holds Kubernetes cluster configuration +type Config struct { + KubernetesVersion string `yaml:"kubernetes_version"` + PodCIDR string `yaml:"pod_cidr"` + ServiceCIDR string `yaml:"service_cidr"` + CNIPlugin string `yaml:"cni_plugin"` + CalicoVersion string `yaml:"calico_version"` + ControlPlaneCPUs int `yaml:"control_plane_cpus"` + ControlPlaneMemory string `yaml:"control_plane_memory"` + ControlPlaneDisk string `yaml:"control_plane_disk"` + WorkerCPUs int `yaml:"worker_cpus"` + WorkerMemory string `yaml:"worker_memory"` + WorkerDisk string `yaml:"worker_disk"` + DNSServers []string `yaml:"dns_servers"` + KubernetesPackages []string `yaml:"kubernetes_packages"` +} + +// LoadDefaultConfig loads the default Kubernetes configuration from the defaults file +func LoadDefaultConfig() (*Config, error) { + defaultsPath := "ansible/defaults/kubernetes.yml" + + data, err := os.ReadFile(defaultsPath) + if err != nil { + return nil, fmt.Errorf("failed to read defaults file: %w", err) + } + + config := &Config{} + err = yaml.Unmarshal(data, config) + if err != nil { + return nil, fmt.Errorf("failed to parse defaults file: %w", err) + } + + return config, nil +} + +// SaveConfig saves the Kubernetes configuration to a temporary file +func SaveConfig(config *Config) (string, error) { + data, err := yaml.Marshal(config) + if err != nil { + return "", fmt.Errorf("failed to marshal config: %w", err) + } + + // Create a temporary directory + tmpDir, err := os.MkdirTemp("", "k8s-provision") + if err != nil { + return "", fmt.Errorf("failed to create temp dir: %w", err) + } + + // Write config to a file + configPath := filepath.Join(tmpDir, "kubernetes.yml") + err = os.WriteFile(configPath, data, 0o644) + if err != nil { + return "", fmt.Errorf("failed to write config file: %w", err) + } + + return configPath, nil +} + +// ProvisionInteractive handles interactive Kubernetes cluster provisioning +func ProvisionInteractive() error { + // Load default configuration + defaultConfig, err := LoadDefaultConfig() + if err != nil { + return err + } + + // Display default settings + fmt.Println("\nCurrent default settings:") + fmt.Printf("Kubernetes Version: %s\n", defaultConfig.KubernetesVersion) + fmt.Printf("Pod CIDR: %s\n", defaultConfig.PodCIDR) + fmt.Printf("Service CIDR: %s\n", defaultConfig.ServiceCIDR) + fmt.Printf("CNI Plugin: %s\n", defaultConfig.CNIPlugin) + fmt.Printf("Control Plane: %d CPUs, %s Memory, %s Disk\n", + defaultConfig.ControlPlaneCPUs, + defaultConfig.ControlPlaneMemory, + defaultConfig.ControlPlaneDisk) + fmt.Printf("Worker Nodes: %d CPUs, %s Memory, %s Disk\n", + defaultConfig.WorkerCPUs, + defaultConfig.WorkerMemory, + defaultConfig.WorkerDisk) + + // Ask if user wants to use default settings + useDefaults, err := interactive.PromptConfirm("Do you want to use these default settings?") + if err != nil { + return err + } + + var config *Config + if useDefaults { + config = defaultConfig + } else { + config = defaultConfig // Start with defaults + + // Ask for each configurable value + k8sVersion, err := interactive.PromptText("Kubernetes Version", config.KubernetesVersion) + if err != nil { + return err + } + config.KubernetesVersion = k8sVersion + + podCIDR, err := interactive.PromptText("Pod CIDR", config.PodCIDR) + if err != nil { + return err + } + config.PodCIDR = podCIDR + + serviceCIDR, err := interactive.PromptText("Service CIDR", config.ServiceCIDR) + if err != nil { + return err + } + config.ServiceCIDR = serviceCIDR + + cniPlugin, err := interactive.PromptSelect("CNI Plugin", []string{"calico", "flannel"}) + if err != nil { + return err + } + config.CNIPlugin = cniPlugin + + if cniPlugin == "calico" { + calicoVersion, err := interactive.PromptText("Calico Version", config.CalicoVersion) + if err != nil { + return err + } + config.CalicoVersion = calicoVersion + } + + // Control plane resources + cpCPUs, err := interactive.PromptIntWithRange("Control Plane CPUs", config.ControlPlaneCPUs, 1, 16) + if err != nil { + return err + } + config.ControlPlaneCPUs = cpCPUs + + cpMemory, err := interactive.PromptText("Control Plane Memory (e.g., 4G)", config.ControlPlaneMemory) + if err != nil { + return err + } + config.ControlPlaneMemory = cpMemory + + cpDisk, err := interactive.PromptText("Control Plane Disk (e.g., 20G)", config.ControlPlaneDisk) + if err != nil { + return err + } + config.ControlPlaneDisk = cpDisk + + // Worker resources + workerCPUs, err := interactive.PromptIntWithRange("Worker CPUs", config.WorkerCPUs, 1, 16) + if err != nil { + return err + } + config.WorkerCPUs = workerCPUs + + workerMemory, err := interactive.PromptText("Worker Memory (e.g., 2G)", config.WorkerMemory) + if err != nil { + return err + } + config.WorkerMemory = workerMemory + + workerDisk, err := interactive.PromptText("Worker Disk (e.g., 20G)", config.WorkerDisk) + if err != nil { + return err + } + config.WorkerDisk = workerDisk + + // Split by comma and trim whitespace + config.DNSServers = []string{} + for _, server := range defaultConfig.DNSServers { + config.DNSServers = append(config.DNSServers, server) + } + } + + // Save configuration to a temporary file + configPath, err := SaveConfig(config) + if err != nil { + return err + } + defer os.RemoveAll(filepath.Dir(configPath)) // Clean up temp dir when done + + // Confirm before proceeding + fmt.Println("\nReady to provision Kubernetes cluster with the selected settings.") + proceed, err := interactive.PromptConfirm("Do you want to proceed?") + if err != nil { + return err + } + + if !proceed { + fmt.Println("Provisioning cancelled.") + return nil + } + + // Run the provision script + fmt.Println("Running provisioning script...") + return runProvisionScript(configPath) +} + +// runProvisionScript runs the actual Kubernetes provisioning +func runProvisionScript(configPath string) error { + // Run the ansible playbook with custom variables + inventory := "ansible/inventories/kubernetes.yml" + playbook := "ansible/playbooks/kubernetes.yml" + + // Check if files exist + if _, err := os.Stat(inventory); os.IsNotExist(err) { + return fmt.Errorf("inventory file does not exist: %s", inventory) + } + if _, err := os.Stat(playbook); os.IsNotExist(err) { + return fmt.Errorf("playbook file does not exist: %s", playbook) + } + + // Run ansible-playbook + return ansible.RunPlaybook(playbook, inventory, []string{"-e", "@" + configPath}) +} + +// Cleanup handles Kubernetes cluster cleanup +func Cleanup() error { + scriptPath := "scripts/cleanup-kubernetes.sh" + + // Check if script exists + if _, err := os.Stat(scriptPath); os.IsNotExist(err) { + return fmt.Errorf("cleanup script does not exist: %s", scriptPath) + } + + // Run the cleanup script + cmd := exec.Command(scriptPath) + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + cmd.Stdin = os.Stdin // Pass stdin for any prompts + + return cmd.Run() +} diff --git a/cli/cmd/provision/main.go b/cli/cmd/provision/main.go new file mode 100644 index 0000000..089c079 --- /dev/null +++ b/cli/cmd/provision/main.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "os" + + "github.com/bxtal-lsn/kubernetes/cli/cmd/provision/cmd" +) + +func main() { + if err := cmd.Execute(); err != nil { + fmt.Fprintf(os.Stderr, "Error: %s\n", err) + os.Exit(1) + } +} diff --git a/cli/cmd/provision/postgres/provision.go b/cli/cmd/provision/postgres/provision.go new file mode 100644 index 0000000..e69de29 diff --git a/cli/go.mod b/cli/go.mod new file mode 100644 index 0000000..43ec878 --- /dev/null +++ b/cli/go.mod @@ -0,0 +1,21 @@ +module github.com/bxtal-lsn/kubernetes/cli + +go 1.22 + +require ( + github.com/AlecAivazis/survey/v2 v2.3.7 + github.com/spf13/cobra v1.9.1 + gopkg.in/yaml.v3 v3.0.1 +) + +require ( + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect + github.com/mattn/go-colorable v0.1.2 // indirect + github.com/mattn/go-isatty v0.0.8 // indirect + github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b // indirect + github.com/spf13/pflag v1.0.6 // indirect + golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f // indirect + golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 // indirect + golang.org/x/text v0.4.0 // indirect +) diff --git a/cli/go.sum b/cli/go.sum new file mode 100644 index 0000000..d1b997e --- /dev/null +++ b/cli/go.sum @@ -0,0 +1,58 @@ +github.com/AlecAivazis/survey/v2 v2.3.7 h1:6I/u8FvytdGsgonrYsVn2t8t4QiRnh6QSTqkkhIiSjQ= +github.com/AlecAivazis/survey/v2 v2.3.7/go.mod h1:xUTIdE4KCOIjsBAE1JYsUPoCqYdZ1reCfTwbto0Fduo= +github.com/Netflix/go-expect v0.0.0-20220104043353-73e0943537d2/go.mod h1:HBCaDeC1lPdgDeDbhX8XFpy1jqjK0IBG8W5K+xYqA0w= +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/creack/pty v1.1.17/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/hinshun/vt10x v0.0.0-20220119200601-820417d04eec/go.mod h1:Q48J4R4DvxnHolD5P8pOtXigYlRuPLGl6moFx3ulM68= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs= +github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= +github.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx8mU= +github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-isatty v0.0.8 h1:HLtExJ+uU2HOZ+wI0Tt5DtUDrx8yhUqDcp7fYERX4CE= +github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b h1:j7+1HpAFS1zy5+Q4qx1fWh90gTKwiN4QCGoY9TWyyO4= +github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo= +github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0= +github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= +github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f h1:v4INt8xihDGvnrfjMDVXGxw9wrfxYyCjk0KbXjhR55s= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.4.0 h1:BrVqGRd7+k1DiOgtnFvAkoQEWQvBc25ouMJM6429SFg= +golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/cli/install.sh b/cli/install.sh new file mode 100644 index 0000000..d237fbe --- /dev/null +++ b/cli/install.sh @@ -0,0 +1,65 @@ +#!/bin/bash + +set -e # Exit on error + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[0;33m' +NC='\033[0m' # No Color + +# Determine OS and architecture +OS=$(uname -s | tr '[:upper:]' '[:lower:]') +ARCH=$(uname -m) + +# Map architecture to Go architecture naming +case $ARCH in + x86_64) + GOARCH="amd64" + ;; + aarch64|arm64) + GOARCH="arm64" + ;; + *) + echo -e "${RED}✗ Error:${NC} Unsupported architecture: $ARCH" + exit 1 + ;; +esac + +# Binary paths +BINARY_NAME="provision" +BINARY_PATH="bin/${OS}_${GOARCH}/${BINARY_NAME}" +INSTALL_DIR="$HOME/.local/bin" + +echo "Installing infrastructure CLI tool..." + +# Check if the binary exists for this platform +if [ ! -f "$BINARY_PATH" ]; then + echo -e "${RED}✗ Error:${NC} Binary not found for your platform: ${OS}_${GOARCH}" + echo "Please compile the binary for your platform or contact the repository maintainer." + exit 1 +fi + +# Create installation directory if it doesn't exist +mkdir -p "$INSTALL_DIR" + +# Copy binary to installation directory +cp "$BINARY_PATH" "$INSTALL_DIR/$BINARY_NAME" +chmod +x "$INSTALL_DIR/$BINARY_NAME" + +echo -e "${GREEN}✓${NC} Installation successful!" + +# Check if installation directory is in PATH +if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then + echo -e "${YELLOW}⚠${NC} The installation directory is not in your PATH." + echo "Please add the following line to your shell profile:" + echo " export PATH=\"\$PATH:$INSTALL_DIR\"" + echo "" + echo "Then restart your shell or run:" + echo " source ~/.bashrc # or your appropriate shell config file" +else + echo -e "${GREEN}✓${NC} The CLI tool is now available in your PATH." +fi + +echo "" +echo "Run '${BINARY_NAME}' to start using the tool." diff --git a/cli/scripts/build-release.sh b/cli/scripts/build-release.sh new file mode 100755 index 0000000..3002ebd --- /dev/null +++ b/cli/scripts/build-release.sh @@ -0,0 +1,76 @@ +#!/bin/bash + +set -e # Exit on error + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[0;33m' +NC='\033[0m' # No Color + +# Set variables +BINARY_NAME="provision" +OUTPUT_DIR="bin" + +echo "Building release binaries for the infrastructure CLI tool..." + +# Check for Go installation +if ! command -v go &> /dev/null; then + echo -e "${RED}✗ Error:${NC} Go is not installed. This script requires Go to build the binaries." + exit 1 +fi + +# Check Go version +GO_VERSION=$(go version | awk '{print $3}' | sed 's/go//') +GO_VERSION_MAJOR=$(echo $GO_VERSION | cut -d. -f1) +GO_VERSION_MINOR=$(echo $GO_VERSION | cut -d. -f2) + +if [ "$GO_VERSION_MAJOR" -lt 1 ] || ([ "$GO_VERSION_MAJOR" -eq 1 ] && [ "$GO_VERSION_MINOR" -lt 18 ]); then + echo -e "${RED}✗ Error:${NC} Go version 1.18 or higher is required. You have $GO_VERSION." + exit 1 +fi + +echo -e "${GREEN}✓${NC} Using Go version $GO_VERSION" + +# Create output directory +mkdir -p $OUTPUT_DIR + +# Define target platforms +PLATFORMS=( + "linux/amd64" + "linux/arm64" + "darwin/amd64" + "darwin/arm64" + "windows/amd64" +) + +# Build for each platform +for PLATFORM in "${PLATFORMS[@]}"; do + OS="${PLATFORM%/*}" + ARCH="${PLATFORM#*/}" + + OUTPUT_NAME="${BINARY_NAME}" + if [ "$OS" = "windows" ]; then + OUTPUT_NAME="${OUTPUT_NAME}.exe" + fi + + echo "Building for ${OS}/${ARCH}..." + + mkdir -p "${OUTPUT_DIR}/${OS}_${ARCH}" + + GOOS=$OS GOARCH=$ARCH go build -o "${OUTPUT_DIR}/${OS}_${ARCH}/${OUTPUT_NAME}" ./cmd/provision + + echo -e "${GREEN}✓${NC} Built ${OS}/${ARCH}" +done + +echo -e "${GREEN}✓${NC} All binaries built successfully!" +echo "" +echo "Binaries are available in the ${OUTPUT_DIR} directory with the following structure:" +echo " ${OUTPUT_DIR}/[os]_[arch]/${BINARY_NAME}" +echo "" +echo "Examples:" +echo " ${OUTPUT_DIR}/linux_amd64/${BINARY_NAME}" +echo " ${OUTPUT_DIR}/darwin_arm64/${BINARY_NAME}" +echo " ${OUTPUT_DIR}/windows_amd64/${BINARY_NAME}.exe" +echo "" +echo "To install the tool, users can run ./install.sh or copy the appropriate binary to their PATH."