UpdateSSHConfig updates the ~/.ssh/config file with the instance connection details
(instanceID, ip string, port int, uuid string, tunnelPorts []int, templatePorts []int)
| 9 | |
| 10 | // UpdateSSHConfig updates the ~/.ssh/config file with the instance connection details |
| 11 | func UpdateSSHConfig(instanceID, ip string, port int, uuid string, tunnelPorts []int, templatePorts []int) error { |
| 12 | homeDir, err := os.UserHomeDir() |
| 13 | if err != nil { |
| 14 | return fmt.Errorf("failed to get home directory: %w", err) |
| 15 | } |
| 16 | |
| 17 | sshDir := filepath.Join(homeDir, ".ssh") |
| 18 | if err := os.MkdirAll(sshDir, 0700); err != nil { |
| 19 | return fmt.Errorf("failed to create .ssh directory: %w", err) |
| 20 | } |
| 21 | |
| 22 | configPath := filepath.Join(sshDir, "config") |
| 23 | |
| 24 | // Read existing config |
| 25 | var existingLines []string |
| 26 | if data, err := os.ReadFile(configPath); err == nil { |
| 27 | existingLines = strings.Split(string(data), "\n") |
| 28 | } |
| 29 | |
| 30 | // Check if entry exists |
| 31 | hostName := fmt.Sprintf("tnr-%s", instanceID) |
| 32 | existingIndex := -1 |
| 33 | inBlock := false |
| 34 | blockStart := -1 |
| 35 | blockEnd := -1 |
| 36 | |
| 37 | for i, line := range existingLines { |
| 38 | trimmed := strings.TrimSpace(line) |
| 39 | if strings.HasPrefix(trimmed, "Host ") { |
| 40 | if inBlock { |
| 41 | blockEnd = i - 1 |
| 42 | break |
| 43 | } |
| 44 | if strings.Contains(trimmed, hostName) { |
| 45 | existingIndex = i |
| 46 | blockStart = i |
| 47 | inBlock = true |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | if inBlock && blockEnd == -1 { |
| 53 | blockEnd = len(existingLines) - 1 |
| 54 | } |
| 55 | |
| 56 | // Build new SSH config entry |
| 57 | keyFile := GetKeyFile(uuid) |
| 58 | var configLines []string |
| 59 | configLines = append(configLines, fmt.Sprintf("Host %s", hostName)) |
| 60 | configLines = append(configLines, fmt.Sprintf(" HostName %s", ip)) |
| 61 | configLines = append(configLines, " User ubuntu") |
| 62 | configLines = append(configLines, fmt.Sprintf(" IdentityFile \"%s\"", keyFile)) |
| 63 | configLines = append(configLines, " IdentitiesOnly yes") |
| 64 | configLines = append(configLines, " IdentityAgent none") |
| 65 | configLines = append(configLines, " StrictHostKeyChecking no") |
| 66 | configLines = append(configLines, fmt.Sprintf(" Port %d", port)) |
| 67 | |
| 68 | // Add port forwarding |
no test coverage detected