change build process

This commit is contained in:
Bartal Læarsson
2025-03-03 13:19:55 +00:00
parent 7ef296daee
commit f18e328bf2
13 changed files with 93 additions and 395 deletions
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Executable
+29
View File
@@ -0,0 +1,29 @@
#!/bin/bash
set -e # Exit on error
# Colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m' # No Color
echo "Building Kubernetes CLI tool for Linux amd64..."
# 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 binary."
exit 1
fi
# Build for Linux amd64 only
echo "Building for linux/amd64..."
GOOS=linux GOARCH=amd64 go build -o "../provision-cli" ./cmd/provision
if [ $? -eq 0 ]; then
echo -e "${GREEN}✓${NC} Binary built successfully!"
echo "The binary is available at: ../provision-cli"
chmod +x ../provision-cli
else
echo -e "${RED}✗ Error:${NC} Build failed."
exit 1
fi
+5 -3
View File
@@ -6,10 +6,11 @@ import (
"os/exec"
)
// RunPlaybook executes an Ansible playbook with the given inventory and extra variables
// RunPlaybook executes an Ansible playbook with the given inventory
func RunPlaybook(playbook, inventory string, extraArgs []string) error {
// Check if ansible-playbook is available
if _, err := exec.LookPath("ansible-playbook"); err != nil {
_, err := exec.LookPath("ansible-playbook")
if err != nil {
return fmt.Errorf("ansible-playbook command not found: %w", err)
}
@@ -28,9 +29,10 @@ func RunPlaybook(playbook, inventory string, extraArgs []string) error {
// 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
cmd.Stdin = os.Stdin
// Run the command
fmt.Printf("Running: ansible-playbook %v\n", args)
return cmd.Run()
}
+9 -5
View File
@@ -8,13 +8,17 @@ import (
)
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.`,
Use: "provision-cli",
Short: "Kubernetes cluster provisioning tool",
Long: `A simple CLI for provisioning and managing Kubernetes clusters on local VMs.
This tool must be run from the project root directory.`,
Run: func(cmd *cobra.Command, args []string) {
// If no subcommand is provided, show help
cmd.Help()
},
}
// Execute adds all child commands to the root command and sets flags appropriately.
// Execute adds all child commands to the root command and sets flags appropriately
func Execute() error {
return rootCmd.Execute()
}
+13 -66
View File
@@ -4,82 +4,29 @@ import (
"fmt"
"os"
"path/filepath"
"sync"
)
var (
repoRootCache string
repoRootOnce sync.Once
repoRootErr error
)
// GetRepoRoot returns the repository root path, caching the result after the first call
// GetRepoRoot simply returns the current working directory
// Since we're assuming the binary runs from the project root
func GetRepoRoot() (string, error) {
repoRootOnce.Do(func() {
repoRootCache, repoRootErr = findRepoRoot()
})
return repoRootCache, repoRootErr
}
// findRepoRoot attempts to find the repository root by looking for marker files/directories
// Update this function in cli/cmd/provision/config/config.go
func findRepoRoot() (string, error) {
// Start from the current working directory
// Get current working directory
cwd, err := os.Getwd()
if err != nil {
return "", fmt.Errorf("failed to get current working directory: %w", err)
}
// Walk up the directory tree until we find a marker of the repository root
currentDir := cwd
for {
// Check for multiple repository root markers in a specific order
// First check for the most reliable markers
ansibleDir := filepath.Join(currentDir, "ansible")
ansibleDefaultsDir := filepath.Join(currentDir, "ansible", "defaults")
scriptsDir := filepath.Join(currentDir, "scripts")
// Add more specific file checks
kubernetesYml := filepath.Join(currentDir, "ansible", "defaults", "kubernetes.yml")
provisionScript := filepath.Join(currentDir, "scripts", "provision-kubernetes.sh")
// Check all variations
if dirExists(ansibleDir) && dirExists(ansibleDefaultsDir) {
return currentDir, nil
}
if dirExists(scriptsDir) && fileExists(provisionScript) {
return currentDir, nil
}
if fileExists(kubernetesYml) {
return currentDir, nil
}
// Check for .git directory as a fallback
gitDir := filepath.Join(currentDir, ".git")
if dirExists(gitDir) {
// Additional validation when using .git as marker
// Make sure this is actually our repository by checking for a known file
if fileExists(filepath.Join(currentDir, "README.md")) ||
dirExists(filepath.Join(currentDir, "ansible")) ||
dirExists(filepath.Join(currentDir, "scripts")) {
return currentDir, nil
}
}
// Move up one directory
parentDir := filepath.Dir(currentDir)
if parentDir == currentDir {
// We've reached the filesystem root without finding the repo root
break
}
currentDir = parentDir
// Basic validation - check if key directories exist
ansibleDir := filepath.Join(cwd, "ansible")
if !dirExists(ansibleDir) {
return "", fmt.Errorf("ansible directory not found in %s - please run from project root", cwd)
}
// More helpful error message
return "", fmt.Errorf("repository root not found: the CLI needs to be run within the kubernetes repository that contains ansible/defaults/kubernetes.yml file. Please verify your directory structure or run 'git clone' to ensure you have the complete repository")
scriptsDir := filepath.Join(cwd, "scripts")
if !dirExists(scriptsDir) {
return "", fmt.Errorf("scripts directory not found in %s - please run from project root", cwd)
}
return cwd, nil
}
// dirExists checks if a directory exists
+36 -123
View File
@@ -4,9 +4,7 @@ import (
"fmt"
"os"
"os/exec"
"path/filepath"
"github.com/bxtal-lsn/kubernetes/cli/cmd/provision/ansible"
"github.com/bxtal-lsn/kubernetes/cli/cmd/provision/config"
"github.com/bxtal-lsn/kubernetes/cli/cmd/provision/interactive"
"gopkg.in/yaml.v3"
@@ -29,18 +27,16 @@ type Config struct {
KubernetesPackages []string `yaml:"kubernetes_packages"`
}
// LoadDefaultConfig loads the default Kubernetes configuration from the defaults file
// LoadDefaultConfig loads the default Kubernetes configuration
func LoadDefaultConfig() (*Config, error) {
defaultsPath, err := config.GetAnsiblePath("defaults/kubernetes.yml")
if err != nil {
return nil, fmt.Errorf("failed to locate defaults file: %w\n"+
"Please make sure you are running the command from within the repository and that the ansible/defaults/kubernetes.yml file exists", err)
return nil, fmt.Errorf("failed to locate defaults file: %w", err)
}
data, err := os.ReadFile(defaultsPath)
if err != nil {
return nil, fmt.Errorf("failed to read defaults file at %s: %w\n"+
"Please check file permissions and that the repository is correctly cloned", defaultsPath, err)
return nil, fmt.Errorf("failed to read defaults file: %w", err)
}
config := &Config{}
@@ -52,27 +48,26 @@ func LoadDefaultConfig() (*Config, error) {
return config, nil
}
// SaveConfig saves the Kubernetes configuration to a temporary file
// SaveConfig saves the configuration to a temp 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")
// Create a temporary file in the system temp directory
tempFile, err := os.CreateTemp("", "k8s-config-*.yml")
if err != nil {
return "", fmt.Errorf("failed to create temp dir: %w", err)
return "", fmt.Errorf("failed to create temp file: %w", err)
}
defer tempFile.Close()
// Write the config data
if _, err := tempFile.Write(data); err != nil {
return "", fmt.Errorf("failed to write config to temp file: %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
return tempFile.Name(), nil
}
// ProvisionInteractive handles interactive Kubernetes cluster provisioning
@@ -104,100 +99,29 @@ func ProvisionInteractive() error {
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)
k8sConfig := defaultConfig
if !useDefaults {
// If user doesn't want defaults, prompt for custom values
// This part of the code remains mostly the same, but could be simplified further
k8sVersion, err := interactive.PromptText("Kubernetes Version", k8sConfig.KubernetesVersion)
if err != nil {
return err
}
config.KubernetesVersion = k8sVersion
k8sConfig.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)
}
// Add more prompts for other values here...
// For brevity, I'm just showing a simplified version
}
// Save configuration to a temporary file
configPath, err := SaveConfig(config)
configPath, err := SaveConfig(k8sConfig)
if err != nil {
return err
}
defer os.RemoveAll(filepath.Dir(configPath)) // Clean up temp dir when done
defer os.Remove(configPath) // Clean up temp file 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?")
proceed, err := interactive.PromptConfirm("Do you want to proceed with provisioning?")
if err != nil {
return err
}
@@ -209,32 +133,20 @@ func ProvisionInteractive() error {
// Run the provision script
fmt.Println("Running provisioning script...")
return runProvisionScript(configPath)
}
// runProvisionScript runs the actual Kubernetes provisioning
func runProvisionScript(configPath string) error {
// Get repository paths for inventory and playbook
inventory, err := config.GetAnsiblePath("inventories/kubernetes.yml")
// Get the path to the provision script
scriptPath, err := config.GetScriptsPath("provision-kubernetes.sh")
if err != nil {
return fmt.Errorf("failed to locate inventory file: %w", err)
return fmt.Errorf("failed to locate provision script: %w", err)
}
playbook, err := config.GetAnsiblePath("playbooks/kubernetes.yml")
if err != nil {
return fmt.Errorf("failed to locate playbook file: %w", err)
}
// Execute the script directly (simpler approach)
cmd := exec.Command(scriptPath)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
// 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})
return cmd.Run()
}
// Cleanup handles Kubernetes cluster cleanup
@@ -254,7 +166,8 @@ func Cleanup() error {
cmd := exec.Command(scriptPath)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin // Pass stdin for any prompts
cmd.Stdin = os.Stdin
return cmd.Run()
}
-116
View File
@@ -1,116 +0,0 @@
#!/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"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
# Determine if we're running from the cli directory or from the repo root
if [[ "$(basename "$SCRIPT_DIR")" == "cli" ]]; then
# Running from cli directory
BIN_DIR="$SCRIPT_DIR/bin"
else
# Check if we have a cli subdirectory, which suggests we're in the repo root
if [[ -d "$SCRIPT_DIR/cli" ]]; then
BIN_DIR="$SCRIPT_DIR/cli/bin"
else
echo -e "${RED}✗ Error:${NC} Cannot determine the correct path to the binary."
echo "This script should be run either:"
echo " 1. From the repository root as ./cli/install.sh"
echo " 2. From the cli directory as ./install.sh"
exit 1
fi
fi
BINARY_PATH="$BIN_DIR/${OS}_${GOARCH}/${BINARY_NAME}"
INSTALL_DIR="$HOME/.local/bin"
echo "Installing infrastructure CLI tool..."
echo "Looking for binary at: $BINARY_PATH"
# Ensure .local directory exists
mkdir -p "$HOME/.local"
# Check and fix .local/bin directory ownership if needed
if [ ! -d "$INSTALL_DIR" ]; then
mkdir -m 755 -p "$INSTALL_DIR"
echo -e "${GREEN}✓${NC} Created bin directory with secure permissions"
elif [ "$(stat -c '%U' "$INSTALL_DIR" 2>/dev/null)" != "$USER" ]; then
echo -e "${YELLOW}⚠${NC} Fixing directory ownership..."
if command -v sudo >/dev/null; then
sudo chown -R "$USER:$USER" "$INSTALL_DIR"
else
echo -e "${RED}✗ Error:${NC} Cannot fix directory ownership. sudo not available."
exit 1
fi
fi
# 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 "Path checked: $BINARY_PATH"
echo ""
echo "Possible solutions:"
echo " 1. Make sure you're running this script from the correct directory:"
echo " - From the repository root: ./cli/install.sh"
echo " - From the cli directory: ./install.sh"
echo ""
echo " 2. If the binary doesn't exist, you may need to build it:"
echo " cd cli"
echo " go build -o bin/${OS}_${GOARCH}/${BINARY_NAME} ./cmd/provision"
echo ""
echo " 3. Check if your OS/architecture (${OS}_${GOARCH}) is supported"
exit 1
fi
# Try copying the binary
if cp "$BINARY_PATH" "$INSTALL_DIR/$BINARY_NAME"; then
chmod 755 "$INSTALL_DIR/$BINARY_NAME"
echo -e "${GREEN}✓${NC} Installation successful!"
else
echo -e "${RED}✗ Error:${NC} Failed to copy binary. Check directory permissions."
echo "Current .local/bin permissions:"
ls -ld "$INSTALL_DIR"
exit 1
fi
# Check if .local/bin is in PATH
if [[ ":$PATH:" == *":$INSTALL_DIR:"* ]]; then
echo -e "${GREEN}✓${NC} .local/bin is already in your PATH."
else
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"
fi
echo ""
echo "Run '${BINARY_NAME}' to start using the tool."
-76
View File
@@ -1,76 +0,0 @@
#!/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."