func main() { if len(os.Args) != 2 { fmt.Printf("Restart VPC\n") fmt.Printf("Usage: cloudstack-vpc-restart <vpcname>\n") os.Exit(1) } vpcName := os.Args[1] apiurl, apikey, secret := config.CloudstackClientConfig() client := cloudstack.NewClient(apiurl, apikey, secret, true) vpcService := cloudstack.NewVPCService(client) if vpcId, vpcName, err := cloudstackutils.FindVpcId(client, vpcName); err != nil { fmt.Printf("Failed to find id for VPC \"%s\": %s\n", vpcName, err.Error()) } else { if _, err := vpcService.RestartVPC(vpcService.NewRestartVPCParams(vpcId)); err != nil { fmt.Printf("Failed to restart VPC \"%s\": %s\n", vpcName, err.Error()) } else { fmt.Printf("Restarting VPC \"%s\"... ", vpcName) } } }
// Utility will return a list of templates sorted by date // Use optional argument to filter using keyword func main() { var keyword string = "" if len(os.Args) == 2 { keyword = os.Args[1] } apiurl, apikey, secret := config.CloudstackClientConfig() client := cloudstack.NewClient(apiurl, apikey, secret, true) templateService := cloudstack.NewTemplateService(client) params := templateService.NewListTemplatesParams("community") if keyword != "" { params.SetKeyword(keyword) } if templates, err := templateService.ListTemplates(params); err != nil { panic(err) } else { sort.Sort(ByDate(templates.Templates)) for _, template := range templates.Templates { fmt.Println(template.Created + " - " + template.Zonename + " - " + template.Name) } } }
// Utility will delete all existing vpn users and create new ones and store generated passwords // in provided password store func main() { if len(os.Args) != 2 { fmt.Printf("Generate VPN users and save passwords in given pass password store\n") fmt.Printf("Usage: cloudstack-vpn-users <PASSWORD_STORE_DIR>\n") os.Exit(1) } fmt.Println("\nWARNING: This script will remove and re-add access with new passwords for ALL users in ALL VPCs.\n") fmt.Println("\nWill start in 5 seconds... [press Ctrl-C to abort]") time.Sleep(5 * time.Second) passwordStoreDir := os.Args[1] // Find usernames fileinfos, _ := ioutil.ReadDir(fmt.Sprintf("%s/users", passwordStoreDir)) users := make([]string, 0) for _, fileinfo := range fileinfos { if fileinfo.IsDir() { users = append(users, fileinfo.Name()) } } // Generate passwords and save them in password store passwords := make([]string, 0) for _, user := range users { passwords = append(passwords, config.GeneratePasswordFor(passwordStoreDir, fmt.Sprintf("users/%s/vpn", user), 32)) } // TODO verify this (uncomment in case it breaks) config.PushPasswords(passwordStoreDir) apiurl, apikey, secret := config.CloudstackClientConfig() client := cloudstack.NewAsyncClient(apiurl, apikey, secret, true) domains := getDomains(client) numberOfDomains := len(domains) processedDomains := make(chan *cloudstack.Domain, numberOfDomains) // Process all domains in parallell for _, domain := range domains { go processDomain(client, domain, users, passwords, processedDomains) } // Wait for all domains to complete for completed := 0; completed < numberOfDomains; { <-processedDomains completed++ fmt.Printf("Waiting for tasks to complete %s/%s\n", strconv.Itoa(completed), strconv.Itoa(numberOfDomains)) } fmt.Println("Complete") }
func main() { if len(os.Args) < 2 { fmt.Printf("Stop VM\n") fmt.Printf("Usage:cloudstack-stop-vm <vm resource id> [-f] \n") fmt.Printf("Example: cloudstack-stop-vm cloudstack_instance.db.1\n") os.Exit(1) } resourceId := os.Args[1] // Should we force stop forced := false if len(os.Args) == 3 { if os.Args[2] == "-f" { fmt.Printf("Will try to forcefully stop vm\n") forced = true } else { fmt.Printf("Unrecognized second parameter. Should be -f\n") os.Exit(1) } } // Read Terraform state if state, err := terraform.ReadState("terraform.tfstate"); err != nil { fmt.Printf("Unable to read terraform.tfstate: %s", err.Error()) os.Exit(1) } else { if resourceState, ok := state.Modules[0].Resources[resourceId]; ok { vmId := resourceState.Primary.Attributes["id"] apiurl, apikey, secret := config.CloudstackClientConfig() client := cloudstack.NewAsyncClient(apiurl, apikey, secret, true) vmService := cloudstack.NewVirtualMachineService(client) params := vmService.NewStopVirtualMachineParams(vmId) params.SetForced(forced) fmt.Printf("Stopping vm with id %s\n", vmId) if res, err := vmService.StopVirtualMachine(params); err != nil { fmt.Printf("Unable to stop vm: %s", err.Error()) os.Exit(1) } else { fmt.Printf("Stopped vm with id %s\n", vmId) fmt.Printf("State is %s\n", res.State) os.Exit(0) } } else { fmt.Println("Instance id not found") os.Exit(1) } } }
func main() { if len(os.Args) != 2 { fmt.Printf("Start VM disk is attached to\n") fmt.Printf("Usage:cloudstack-start-vm-for-disk <disk resource id>\n") fmt.Printf("Example: cloudstack-start-vm-for-disk cloudstack_disk.db.1\n") os.Exit(1) } diskResourceId := os.Args[1] // Read Terraform state if state, err := terraform.ReadState("terraform.tfstate"); err != nil { fmt.Printf("Unable to read terraform.tfstate: %s", err.Error()) os.Exit(1) } else { if resourceState, ok := state.Modules[0].Resources[diskResourceId]; ok { vmId := resourceState.Primary.Attributes["virtual_machine_id"] apiurl, apikey, secret := config.CloudstackClientConfig() client := cloudstack.NewAsyncClient(apiurl, apikey, secret, true) vmService := cloudstack.NewVirtualMachineService(client) params := vmService.NewStartVirtualMachineParams(vmId) fmt.Printf("Starting vm with id %s\n", vmId) if res, err := vmService.StartVirtualMachine(params); err != nil { fmt.Printf("Unable to start vm: %s", err.Error()) os.Exit(1) } else { fmt.Printf("Started vm with id %s\n", vmId) fmt.Printf("State is %s\n", res.State) os.Exit(0) } } else { fmt.Println("Disk id not found") os.Exit(1) } } }
func main() { if len(os.Args) != 2 { fmt.Printf("Stop VMs in VPC\n") fmt.Printf("Usage: cloudstack-vm-stop <vpcname>\n") os.Exit(1) } vpcName := os.Args[1] apiurl, apikey, secret := config.CloudstackClientConfig() client := cloudstack.NewClient(apiurl, apikey, secret, true) if vpcId, vpcName, err := cloudstackutils.FindVpcId(client, vpcName); err != nil { fmt.Printf("Failed to find id for VPC \"%s\": %s\n", vpcName, err.Error()) } else { vmService := cloudstack.NewVirtualMachineService(client) virtualMachinesParams := vmService.NewListVirtualMachinesParams() virtualMachinesParams.SetVpcid(vpcId) virtualMachinesParams.SetState("Running") if vms, err := vmService.ListVirtualMachines(virtualMachinesParams); err != nil { fmt.Printf("Failed to list VMs in VPC \"%s\": %s\n", vpcName, err.Error()) } else { if vms.Count > 0 { for _, vm := range vms.VirtualMachines { fmt.Printf("Stopping VM %s / %s \n", vm.Displayname, vm.Name) if _, err := vmService.StopVirtualMachine(vmService.NewStopVirtualMachineParams(vm.Id)); err != nil { fmt.Printf("Failed to stop VM with id %s: %s\n", vm.Id, err.Error()) } else { fmt.Printf("VM with id %s stopped\n", vm.Id) } } } else { fmt.Printf("No running VMs in %s\n", vpcName) } } } }
// Utility to enable remote access VPN on an // Apache Cloudstack VPC // // If 10.x.0.0/16 is the CIDR of your VPC, // the vpn concentrator will distribute IPs in // Will give you an IP in the 10.(x+100).0.0 CIDR // // To enable routing to this network: // // sudo route add 10.x.0.0/16 10.(x+100).0.1 // func main() { if len(os.Args) < 2 { fmt.Printf("Enable remote VPN access on VPC\n") fmt.Printf("Usage: cloudstack-vpn <vpcname> [<PASSWORD_STORE_DIR>]\n") os.Exit(1) } vpcNameProvided := os.Args[1] apiurl, apikey, secret := config.CloudstackClientConfig() client := cloudstack.NewClient(apiurl, apikey, secret, true) asyncClient := cloudstack.NewAsyncClient(apiurl, apikey, secret, true) if vpcId, vpcName, err := cloudstackutils.FindVpcId(client, vpcNameProvided); err != nil { fmt.Printf("Failed to find id for VPC \"%s\": %s\n", vpcNameProvided, err.Error()) fmt.Println("Hint: Using wrong user?") } else { fmt.Printf("VPC id %s found for vpc name \"%s\"\n", vpcId, vpcName) if ipAddressId, err := findPublicIPAddressForVPC(client, vpcId); err != nil { fmt.Printf("Failed to find public IP address for VPC id %s: %s", vpcId, err.Error()) } else { var vpn *cloudstack.RemoteAccessVpn if vpnExisting, err := findRemoteAccessVPN(client, ipAddressId); err != nil { fmt.Printf("Failed to find remote access VPN: %s", err.Error()) } else if vpnExisting == nil { fmt.Printf("Remote Access VPN not enabled for VPC, creating new one\n") if vpnAddressRange, err := findVPNAddressRange(client, vpcId); err != nil { fmt.Printf("Failed to find cidr range: %s\n", err) } else { fmt.Printf("VPN address range %s \n", vpnAddressRange) if vpnCreated, err := createRemoteAccessVPN(asyncClient, ipAddressId, vpnAddressRange); err != nil { fmt.Printf("Failed to create new remote access VPN: %s", err.Error()) } else { vpn = vpnCreated } } } else { vpn = vpnExisting } if vpn != nil { fmt.Printf("VPN connection details for VPC \"%s\":\n", vpcName) fmt.Printf("IP address: %s\n", vpn.Publicip) fmt.Printf("Preshared secret: %s\n", vpn.Presharedkey) if len(os.Args) == 3 { fmt.Printf("Saving preshared secret to password store in : %s\n", os.Args[2]) config.InsertPasswordFor(os.Args[2], fmt.Sprintf("shared/%s", vpcName), vpn.Presharedkey) } } } } }
// Utility will copy templates matching keyword in from zone in to to zone func main() { if len(os.Args) != 4 { fmt.Printf("Copy templates into other zone\n") fmt.Printf("Usage: cloudstack-templates-copy <keyword> <from zone> <to zone>\n") os.Exit(1) } keyword := os.Args[1] fromZone := os.Args[2] toZone := os.Args[3] apiurl, apikey, secret := config.CloudstackClientConfig() asyncclient := cloudstack.NewAsyncClient(apiurl, apikey, secret, true) // Lookup zone ids service := cloudstack.NewZoneService(asyncclient) var fromId = "" if from, _, err := service.GetZoneByName(fromZone); err != nil { panic(err) } else { fromId = from.Id } var toId = "" if to, _, err := service.GetZoneByName(toZone); err != nil { panic(err) } else { toId = to.Id } // Lookup templates templateService := cloudstack.NewTemplateService(asyncclient) // Can only own templates listTemplatesParams := templateService.NewListTemplatesParams("self") listTemplatesParams.SetKeyword(keyword) listTemplatesParams.SetZoneid(fromId) if templates, err := templateService.ListTemplates(listTemplatesParams); err != nil { panic(err) } else { for _, template := range templates.Templates { fmt.Println("Copy template", template.Name, "(", template.Id, ") from zone \"", fromZone, "\" (", fromId, ") to zone \"", toZone, "\" with Id (", toId, ")") copyTemplateParams := templateService.NewCopyTemplateParams(toId, template.Id) copyTemplateParams.SetSourcezoneid(fromId) if res, err := templateService.CopyTemplate(copyTemplateParams); err != nil { panic(err) } else { fmt.Println(res.Name) } } } }