package rancher import ( "fmt" "log" "os" "../util" ) type Node struct { ClusterName string `json:"clusterName"` Roles []string `json:"roles"` IP string `json:"ip"` SSHUsername string `json:"sshUsername"` SSHPassword string `json:"sshPassword"` SSHPort int `json:"sshPort"` } type RancherConfig struct { RancherURL string `json:"rancherURL"` BearerToken string `json:"bearerToken"` } func isRancherInstalled(ip, username, password string, sshPort int) (bool, error) { // 检查Rancher容器是否已运行 checkRancherCommand := "sudo docker ps --format '{{.Image}}' | grep -q rancher/rancher:v2.5.17" _, err := util.SSHExec(ip, username, password, checkRancherCommand, sshPort) if err != nil { // 如果执行命令出错,则说明Rancher未安装或发生其他错误 return false, fmt.Errorf("failed to check Rancher installation: %v", err) } return true, nil } func InstallRancher(ip, username, password string, sshPort int) error { rancherInstalled, err := isRancherInstalled(ip, username, password, sshPort) if err == nil { return nil } if !rancherInstalled { // 安装Rancher命令 rancherCommand := "sudo docker run --privileged -d --restart=unless-stopped -p 8081:80 -p 8443:443 -v /opt/rancher:/var/lib/rancher registry.cn-hangzhou.aliyuncs.com/rancher/rancher:v2.5.17" _, err = util.SSHExec(ip, username, password, rancherCommand, sshPort) if err != nil { return fmt.Errorf("failed to install Rancher: %v", err) } } else { fmt.Println("Rancher is already installed on the remote server.") } return nil } func InstallDockerAndRancher(ip, username, password string, sshPort int) error { // 安装Docker命令 err := util.InstallDocker(ip, username, password, sshPort) if err != nil { return err } // 安装Rancher命令 err = InstallRancher(ip, username, password, sshPort) if err != nil { return err } return nil } func main() { clusterName := "kubernetus" nodes := []Node{ { ClusterName: clusterName, Roles: []string{"etcd", "controlplane", "worker"}, IP: "192.168.20.189", SSHUsername: "basic", SSHPassword: "123", SSHPort: 22, }, { ClusterName: clusterName, Roles: []string{"worker"}, IP: "192.168.20.10", SSHUsername: "basic", SSHPassword: "123", SSHPort: 22, }, { ClusterName: clusterName, Roles: []string{"worker"}, IP: "192.168.20.115", SSHUsername: "basic", SSHPassword: "alien123", SSHPort: 22, }, // Add more nodes here if needed } //install rancher on master node err := InstallDockerAndRancher(nodes[0].IP, nodes[0].SSHUsername, nodes[0].SSHPassword, nodes[0].SSHPort) if err != nil { log.Fatalf("Failed to install Rancher: %v", err) } os.Exit(0) }