add go cli initial
This commit is contained in:
@@ -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()
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user