add firewall rules option

This commit is contained in:
2025-11-16 17:03:39 +07:00
parent 36fa9644b4
commit 1655151d29
3 changed files with 141 additions and 18 deletions

View File

@@ -194,9 +194,16 @@ func createProxmoxVM(config *Config) error {
"--serial0", "socket",
"--vga", "serial0",
},
}
if config.Firewall {
commands = append(commands, []string{"qm", "set", fmt.Sprintf("%d", config.VMID), "--firewall", "1"})
}
commands = append(commands, [][]string{
{"qm", "template", fmt.Sprintf("%d", config.VMID)},
{"rm", "-f", remotePath},
}
}...)
for _, cmdArgs := range commands {
fmt.Printf("Running: %s\n", strings.Join(cmdArgs, " "))
@@ -232,12 +239,65 @@ func createProxmoxVM(config *Config) error {
}
}
if config.Firewall && len(config.FirewallRules) > 0 {
if err := configureFirewallRules(config, sshCmd); err != nil {
return fmt.Errorf("failed to configure firewall rules: %w", err)
}
}
fmt.Printf("\nTemplate %s (ID: %d) created successfully!\n", config.VMName, config.VMID)
fmt.Printf("You can clone it with: qm clone %d <new-vm-id> --name <new-vm-name>\n", config.VMID)
return nil
}
func configureFirewallRules(config *Config, sshCmd func(args ...string) *exec.Cmd) error {
fmt.Println("Configuring firewall rules...")
firewallConfig := "[OPTIONS]\nenable: 1\n\n[RULES]\n"
for _, rule := range config.FirewallRules {
ruleLine := fmt.Sprintf("%s %s", strings.ToUpper(rule.Type), strings.ToUpper(rule.Action))
if rule.Protocol != "" {
ruleLine += fmt.Sprintf(" -p %s", rule.Protocol)
}
if rule.Dport != "" {
ruleLine += fmt.Sprintf(" -dport %s", rule.Dport)
}
if rule.Sport != "" {
ruleLine += fmt.Sprintf(" -sport %s", rule.Sport)
}
if rule.Source != "" {
ruleLine += fmt.Sprintf(" -source %s", rule.Source)
}
if rule.Dest != "" {
ruleLine += fmt.Sprintf(" -dest %s", rule.Dest)
}
if rule.Comment != "" {
ruleLine += fmt.Sprintf(" -log nolog # %s", rule.Comment)
}
firewallConfig += ruleLine + "\n"
}
firewallPath := fmt.Sprintf("/etc/pve/firewall/%d.fw", config.VMID)
createCmd := sshCmd("bash", "-c", fmt.Sprintf("cat > %s << 'EOF'\n%sEOF", firewallPath, firewallConfig))
var stdout, stderr bytes.Buffer
createCmd.Stdout = &stdout
createCmd.Stderr = &stderr
if err := createCmd.Run(); err != nil {
fmt.Println(stdout.String())
fmt.Println(stderr.String())
return fmt.Errorf("failed to create firewall config: %w", err)
}
fmt.Printf("Firewall rules configured: %s\n", firewallPath)
return nil
}
func listAvailableStorage(config *Config) error {
fmt.Printf("Detecting available storage on %s...\n", config.ProxmoxHost)