Example #1
0
// 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")

}
Example #2
0
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)
		}

	}

}
Example #3
0
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)
		}

	}

}
Example #4
0
// 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)
				}
			}

		}

	}

}
Example #5
0
// Run implements the packer.Builder interface.
func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) {
	b.ui = ui

	// Create a CloudStack API client.
	client := cloudstack.NewAsyncClient(
		b.config.APIURL,
		b.config.APIKey,
		b.config.SecretKey,
		!b.config.SSLNoVerify,
	)

	// Set the time to wait before timing out
	client.AsyncTimeout(int64(b.config.AsyncTimeout.Seconds()))

	// Some CloudStack service providers only allow HTTP GET calls.
	client.HTTPGETOnly = b.config.HTTPGetOnly

	// Set up the state.
	state := new(multistep.BasicStateBag)
	state.Put("client", client)
	state.Put("config", b.config)
	state.Put("hook", hook)
	state.Put("ui", ui)

	// Build the steps.
	steps := []multistep.Step{
		&stepPrepareConfig{},
		&stepCreateInstance{},
		&stepSetupNetworking{},
		&communicator.StepConnect{
			Config:    &b.config.Comm,
			Host:      commHost,
			SSHConfig: sshConfig,
		},
		&common.StepProvision{},
		&stepShutdownInstance{},
		&stepCreateTemplate{},
	}

	// Configure the runner.
	if b.config.PackerDebug {
		b.runner = &multistep.DebugRunner{
			Steps:   steps,
			PauseFn: common.MultistepDebugFn(ui),
		}
	} else {
		b.runner = &multistep.BasicRunner{Steps: steps}
	}

	// Run the steps.
	b.runner.Run(state)

	// If there are no templates, then just return
	template, ok := state.Get("template").(*cloudstack.CreateTemplateResponse)
	if !ok || template == nil {
		return nil, nil
	}

	// Build the artifact and return it
	artifact := &Artifact{
		client:   client,
		config:   b.config,
		template: template,
	}

	return artifact, nil
}
Example #6
0
// newCSCloud creates a new instance of CSCloud.
func newCSCloud(cfg *CSConfig) (*CSCloud, error) {
	client := cloudstack.NewAsyncClient(cfg.Global.APIURL, cfg.Global.APIKey, cfg.Global.SecretKey, !cfg.Global.SSLNoVerify)

	return &CSCloud{client, cfg.Global.ProjectID, cfg.Global.Zone}, nil
}
Example #7
0
// 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)
			}

		}

	}

}
func (d *Driver) getClient() *cloudstack.CloudStackClient {
	cs := cloudstack.NewAsyncClient(d.ApiURL, d.ApiKey, d.SecretKey, false)
	cs.HTTPGETOnly = d.HTTPGETOnly
	cs.AsyncTimeout(d.JobTimeOut)
	return cs
}
Example #9
0
// Client() returns a new CloudStack client.
func (c *Config) NewClient() (*cloudstack.CloudStackClient, error) {
	cs := cloudstack.NewAsyncClient(c.ApiURL, c.ApiKey, c.SecretKey, false)
	cs.AsyncTimeout(180)
	return cs, nil
}
Example #10
0
// NewClient returns a new CloudStack client.
func (c *Config) NewClient() (*cloudstack.CloudStackClient, error) {
	cs := cloudstack.NewAsyncClient(c.APIURL, c.APIKey, c.SecretKey, false)
	cs.HTTPGETOnly = c.HTTPGETOnly
	cs.AsyncTimeout(c.Timeout)
	return cs, nil
}