Example #1
0
// NewClientFromSettingsFile returns a new Azure management
// client created using a publish settings file.
func (c *Config) NewClientFromSettingsFile() (*Client, error) {
	if _, err := os.Stat(c.SettingsFile); os.IsNotExist(err) {
		return nil, fmt.Errorf("Publish Settings file %q does not exist!", c.SettingsFile)
	}

	mc, err := management.ClientFromPublishSettingsFile(c.SettingsFile, c.SubscriptionID)
	if err != nil {
		return nil, nil
	}

	return &Client{
		mgmtClient:           mc,
		affinityGroupClient:  affinitygroup.NewClient(mc),
		hostedServiceClient:  hostedservice.NewClient(mc),
		secGroupClient:       networksecuritygroup.NewClient(mc),
		osImageClient:        osimage.NewClient(mc),
		sqlClient:            sql.NewClient(mc),
		storageServiceClient: storageservice.NewClient(mc),
		vmClient:             virtualmachine.NewClient(mc),
		vmDiskClient:         virtualmachinedisk.NewClient(mc),
		vmImageClient:        virtualmachineimage.NewClient(mc),
		vnetClient:           virtualnetwork.NewClient(mc),
		mutex:                &sync.Mutex{},
	}, nil
}
func deleteHostedService(t *testing.T, client management.Client, vmname string) {
	t.Logf("Deleting hosted service: %s", vmname)
	if err := Await(client, func() (management.OperationID, error) {
		return hostedservice.NewClient(client).DeleteHostedService(vmname, true)
	}); err != nil {
		t.Error(err)
	}
}
Example #3
0
func main() {
	psPath := "path/to/publishSettings"

	dnsName := "test-vm-from-go"
	storageAccount := "mystorageaccount"
	location := "central us"
	vmSize := "Small"
	vmImage := "b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu-14_04-LTS-amd64-server-20140724-en-us-30GB"
	userName := "******"
	userPassword := "******"

	fmt.Println("Create client")
	client, err := management.ClientFromPublishSettingsFile(fmt.Sprintf("%s.publishsettings", psPath), "")
	if err != nil {
		panic(err)
	}

	fmt.Println("Create hosted service")
	if err := hostedservice.NewClient(client).CreateHostedService(hostedservice.CreateHostedServiceParameters{
		ServiceName: dnsName,
		Location:    location,
		Label:       base64.StdEncoding.EncodeToString([]byte(dnsName))}); err != nil {
		panic(err)
	}

	fmt.Println("Create storage account")
	_, err = storageservice.NewClient(client).CreateStorageService(storageservice.StorageAccountCreateParameters{
		ServiceName: storageAccount,
		Label:       base64.URLEncoding.EncodeToString([]byte(storageAccount)),
		Location:    location,
		AccountType: storageservice.AccountTypeStandardLRS})
	if err != nil {
		panic(err)
	}

	fmt.Println("Create virtual machine")
	role := vmutils.NewVMConfiguration(dnsName, vmSize)
	vmutils.ConfigureDeploymentFromPlatformImage(
		&role,
		vmImage,
		fmt.Sprintf("http://%s.blob.core.windows.net/%s/%s.vhd", storageAccount, dnsName, dnsName),
		"")
	vmutils.ConfigureForLinux(&role, dnsName, userName, userPassword)
	vmutils.ConfigureWithPublicSSH(&role)

	fmt.Println("Deploy")
	operationID, err := virtualmachine.NewClient(client).
		CreateDeployment(role, dnsName, virtualmachine.CreateDeploymentOptions{})
	if err != nil {
		panic(err)
	}
	fmt.Println("Waiting...")
	if err = client.WaitForOperation(operationID, nil); err != nil {
		panic(err)
	}
}
Example #4
0
//
// configureForLinux sets up the VM role for Linux specific configuration
//
// Paramters:
//   role: role that needs to be updated with Linux configuration
//   dnsName: name of the machine that we are trying to create
//
// Returns:
//   error: errors from reading certs, getting thumbprint and adding
//   certificate to hostedservice
//
func (d *Driver) configureForLinux(role *virtualmachine.Role, dnsName string) error {

	// Get the Azure client
	client, err := d.getClient()
	if err != nil {
		return err
	}

	mediaLink := fmt.Sprintf("http://%s.blob.core.windows.net/vhds/%s.vhd",
		d.StorageAccount, dnsName)

	// Setup the image configuration
	vmutils.ConfigureDeploymentFromPlatformImage(
		role,
		d.Image,
		mediaLink,
		"")

	// Read the certificate
	data, err := ioutil.ReadFile(d.azureCertPath())
	if err != nil {
		return err
	}

	// Add the certificate to the hostedservice
	if _, err := hostedservice.NewClient(client).AddCertificate(dnsName, data, "pfx", ""); err != nil {
		return err
	}

	thumbPrint, err := getServiceCertFingerprint(d.azureCertPath())
	if err != nil {
		return err
	}

	vmutils.ConfigureForLinux(role, dnsName, d.SSHUser, d.UserPassword, thumbPrint)
	vmutils.ConfigureWithPublicSSH(role)

	role.UseCertAuth = true
	role.CertPath = d.azureCertPath()

	// Attach VM to a specific subnet
	if d.Subnet != "" {
		err = vmutils.ConfigureWithSubnet(role, d.Subnet)
		if err != nil {
			log.Error("failed to configure subnet:", d.Subnet, ", err:", err)
			return err
		}
		log.Debug("subnet is:", d.Subnet)
	}

	return nil
}
func (s *StepCreateService) Cleanup(state multistep.StateBag) {
	client := state.Get(constants.RequestManager).(management.Client)
	hsc := hostedservice.NewClient(client)
	ui := state.Get(constants.Ui).(packer.Ui)

	if res := state.Get(constants.SrvExists).(int); res == 1 {
		ui.Say("Removing temporary Azure service and its deployments, if any...")
		errorMsg := "Error removing temporary Azure service: %s"

		if err := retry.ExecuteAsyncOperation(client, func() (management.OperationID, error) {
			return hsc.DeleteHostedService(s.TmpServiceName, true)
		}); err != nil {
			ui.Error(fmt.Sprintf(errorMsg, err))
			return
		}
	}
}
func createRoleConfiguration(t *testing.T, client management.Client, role vm.Role, location string) {
	vmc := vm.NewClient(client)
	hsc := hostedservice.NewClient(client)
	vmname := role.RoleName

	if err := hsc.CreateHostedService(hostedservice.CreateHostedServiceParameters{
		ServiceName: vmname, Location: location,
		Label: base64.StdEncoding.EncodeToString([]byte(vmname))}); err != nil {
		t.Error(err)
	}

	if err := Await(client, func() (management.OperationID, error) {
		return vmc.CreateDeployment(role, vmname, vm.CreateDeploymentOptions{})
	}); err != nil {
		t.Error(err)
	}
}
Example #7
0
func (d *Driver) PreCreateCheck() error {
	if err := d.setUserSubscription(); err != nil {
		return err
	}

	client, err := d.getClient()
	if err != nil {
		return err
	}

	// check azure DNS to make sure name is available
	_, err = hostedservice.NewClient(client).CheckHostedServiceNameAvailability(d.MachineName)
	if err != nil {
		return err
	}

	return nil
}
func main() {
	dnsName := "test-vm-from-go"
	storageAccount := "gosdktest"
	location := "West US"
	vmSize := "Small"
	vmImage := "b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu-14_04-LTS-amd64-server-20140724-en-us-30GB"
	userName := "******"
	userPassword := "******"

	client, err := management.ClientFromPublishSettingsFile("/Users/niklasg/Downloads/Internal-credentials.publishsettings", "")
	if err != nil {
		panic(err)
	}

	// create hosted service
	if err := hostedservice.NewClient(client).CreateHostedService(hostedservice.CreateHostedServiceParameters{
		ServiceName: dnsName,
		Location:    location,
		Label:       base64.StdEncoding.EncodeToString([]byte(dnsName))}); err != nil {

		if azErr, ok := err.(management.AzureError); !ok || azErr.Code != "ConflictError" {
			panic(err)
		}
	}

	// create virtual machine
	role := vmutils.NewVMConfiguration(dnsName, vmSize)
	vmutils.ConfigureDeploymentFromPlatformImage(
		&role,
		vmImage,
		fmt.Sprintf("http://%s.blob.core.windows.net/sdktest/%s.vhd", storageAccount, dnsName),
		"")
	vmutils.ConfigureForLinux(&role, dnsName, userName, userPassword)
	vmutils.ConfigureWithPublicSSH(&role)

	operationID, err := virtualmachine.NewClient(client).
		CreateDeployment(role, dnsName, virtualmachine.CreateDeploymentOptions{})
	if err != nil {
		panic(err)
	}
	if err := client.WaitForOperation(operationID, nil); err != nil {
		panic(err)
	}
}
Example #9
0
func Example() {
	dnsName := "test-vm-from-go"
	storageAccount := "mystorageaccount"
	location := "West US"
	vmSize := "Small"
	vmImage := "b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu-14_04-LTS-amd64-server-20140724-en-us-30GB"
	userName := "******"
	userPassword := "******"

	client, err := management.ClientFromPublishSettingsFile("path/to/downloaded.publishsettings", "")
	if err != nil {
		panic(err)
	}

	// create hosted service
	if err := hostedservice.NewClient(client).CreateHostedService(hostedservice.CreateHostedServiceParameters{
		ServiceName: dnsName,
		Location:    location,
		Label:       base64.StdEncoding.EncodeToString([]byte(dnsName))}); err != nil {
		panic(err)
	}

	// create virtual machine
	role := NewVMConfiguration(dnsName, vmSize)
	ConfigureDeploymentFromPlatformImage(
		&role,
		vmImage,
		fmt.Sprintf("http://%s.blob.core.windows.net/sdktest/%s.vhd", storageAccount, dnsName),
		"")
	ConfigureForLinux(&role, dnsName, userName, userPassword)
	ConfigureWithPublicSSH(&role)

	operationID, err := virtualmachine.NewClient(client).
		CreateDeployment(role, dnsName, virtualmachine.CreateDeploymentOptions{})
	if err != nil {
		panic(err)
	}
	err = client.WaitForOperation(operationID, nil)
	if err != nil {
		panic(err)
	}
}
Example #10
0
func (c *Config) NewClientFromSettingsData() (*Client, error) {
	mc, err := management.ClientFromPublishSettingsData(c.Settings, c.SubscriptionID)
	if err != nil {
		return nil, nil
	}

	return &Client{
		mgmtClient:           mc,
		affinityGroupClient:  affinitygroup.NewClient(mc),
		hostedServiceClient:  hostedservice.NewClient(mc),
		secGroupClient:       networksecuritygroup.NewClient(mc),
		osImageClient:        osimage.NewClient(mc),
		sqlClient:            sql.NewClient(mc),
		storageServiceClient: storageservice.NewClient(mc),
		vmClient:             virtualmachine.NewClient(mc),
		vmDiskClient:         virtualmachinedisk.NewClient(mc),
		vmImageClient:        virtualmachineimage.NewClient(mc),
		vnetClient:           virtualnetwork.NewClient(mc),
		mutex:                &sync.Mutex{},
	}, nil
}
Example #11
0
func (d *Driver) Remove() error {

	if err := d.setUserSubscription(); err != nil {
		return err
	}

	client, err := d.getClient()
	if err != nil {
		return err
	}

	hostedClient := hostedservice.NewClient(client)
	availabilityResponse, err := hostedClient.CheckHostedServiceNameAvailability(d.MachineName)
	if err != nil {
		log.Error("Failed to check service name availability")
		return err
	}

	if availabilityResponse.Result == true {
		log.Error("Hosted service does not exist and cannot be deleted")
		return err
	}

	// Note: this only removes the VHD file of a hosted service reliably.
	// An associated xxx.status file is left behind for certain deletions
	opID, err := hostedClient.DeleteHostedService(d.MachineName, true)
	if err != nil {
		log.Error("Error deleting hosted service. Err:", err)
		return err
	}

	if err = client.WaitForOperation(opID, nil); err != nil {
		log.Error("Error deleting hosted service. Err:", err)
		return err
	}

	return nil
}
func (s *StepUploadCertificate) Run(state multistep.StateBag) multistep.StepAction {
	client := state.Get(constants.RequestManager).(management.Client)
	ui := state.Get("ui").(packer.Ui)
	errorMsg := "Error Uploading Temporary Certificate: %s"
	var err error

	ui.Say("Uploading Temporary Certificate...")

	certData := []byte(state.Get(constants.Certificate).(string))

	if err = retry.ExecuteAsyncOperation(client, func() (management.OperationID, error) {
		return hostedservice.NewClient(client).AddCertificate(s.TmpServiceName, certData, hostedservice.CertificateFormatPfx, "")
	}); err != nil {
		err := fmt.Errorf(errorMsg, err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	state.Put(constants.CertUploaded, 1)

	return multistep.ActionContinue
}
func (s *StepCreateService) Run(state multistep.StateBag) multistep.StepAction {
	client := state.Get(constants.RequestManager).(management.Client)
	hsc := hostedservice.NewClient(client)
	ui := state.Get(constants.Ui).(packer.Ui)

	errorMsg := "Error creating temporary Azure service: %s"

	ui.Say("Creating temporary Azure service...")

	if err := hsc.CreateHostedService(hostedservice.CreateHostedServiceParameters{
		ServiceName: s.TmpServiceName,
		Location:    s.Location,
		Label:       base64.StdEncoding.EncodeToString([]byte(s.TmpServiceName)),
	}); err != nil {
		err := fmt.Errorf(errorMsg, err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	state.Put(constants.SrvExists, 1)

	return multistep.ActionContinue
}
Example #14
0
func (d *Driver) Create() error {

	var vmDeploymentOptions virtualmachine.CreateDeploymentOptions

	if err := d.setUserSubscription(); err != nil {
		return err
	}

	log.Info("Creating Azure machine...")
	client, err := d.getClient()
	if err != nil {
		return err
	}

	dnsName := d.MachineName

	// 1. Create the hosted service
	if err := hostedservice.NewClient(client).CreateHostedService(hostedservice.CreateHostedServiceParameters{
		ServiceName: dnsName,
		Location:    d.Location,
		Label:       base64.StdEncoding.EncodeToString([]byte(dnsName))}); err != nil {
		return err
	}

	// 2. Generate certificates
	log.Debug("Generating certificate for Azure...")
	if err := d.generateCertForAzure(); err != nil {
		return err
	}

	// 3. Setup VM configuration for creation
	log.Debug("Setting up VM configuration...")
	var operationID management.OperationID

	role := vmutils.NewVMConfiguration(dnsName, d.Size)
	if d.OS == drivers.LINUX {
		err := d.configureForLinux(&role, dnsName)
		if err != nil {
			goto fail
		}

	} else {
		d.configureForWindows(&role, dnsName)
	}

	log.Debug("Authorizing docker ports...")
	if err := d.addDockerEndpoints(&role); err != nil {
		goto fail
	}

	// 4. Create the VM
	if d.VNet != "" {
		vmDeploymentOptions = virtualmachine.CreateDeploymentOptions{
			VirtualNetworkName: d.VNet,
		}
	} else {
		vmDeploymentOptions = virtualmachine.CreateDeploymentOptions{}
	}

	operationID, err = virtualmachine.NewClient(client).
		CreateDeployment(role, dnsName, vmDeploymentOptions)
	if err != nil {
		goto fail
	}

	// 5. Wait for operation
	err = client.WaitForOperation(operationID, nil)
	if err != nil {
		goto fail
	}
	goto success

fail:
	hostedservice.NewClient(client).DeleteHostedService(dnsName, true)
	return err

success:
	return nil
}
Example #15
0
//
// configureForWindows sets up the VM role for Windows specific configuration
//
// Paramters:
//   role: role that needs to be updated with Windows configuration
//   dnsName: name of the machine that we are trying to create
//
// Returns:
//   None
//
func (d *Driver) configureForWindows(role *virtualmachine.Role, dnsName string) error {

	// Get the Azure client
	client, err := d.getClient()
	if err != nil {
		return err
	}

	mediaLocation := fmt.Sprintf("http://%s.blob.core.windows.net/vhds/%s.vhd",
		d.StorageAccount, dnsName)

	// Setup the image configuration
	vmutils.ConfigureDeploymentFromPlatformImage(
		role,
		d.Image,
		mediaLocation,
		"")
	log.Debug("Configured deployment from platform image")

	vmutils.ConfigureForWindows(role, dnsName, d.SSHUser, d.UserPassword, true, "")
	log.Debug("Configured for windows")

	vmutils.ConfigureWithPublicSSH(role)
	log.Debug("Configured for SSH")

	vmutils.ConfigureWithPublicRDP(role)
	log.Debug("Configured for RDP")

	vmutils.ConfigureWithPublicPowerShell(role)
	log.Debug("Configured with Powershell")

	vmutils.ConfigureWithExternalPort(role, "WinRMu", 5985, 5985,
		virtualmachine.InputEndpointProtocolTCP)
	log.Debug("Configured WinRM port 5985")

	// Read the certificate
	data, err := ioutil.ReadFile(d.azureCertPath())
	if err != nil {
		return err
	}
	log.Debug("Read certificate from Azure cert path: ", d.azureCertPath())

	// Add the certificate to the hostedservice
	if _, err := hostedservice.NewClient(client).AddCertificate(dnsName, data, "pfx", ""); err != nil {
		log.Error("failed to add certificate:", err)
		return err
	}
	log.Debug("Added certificate to hostedservice")

	vmutils.ConfigureWinRMOverHTTP(role)
	log.Debug("Configured WinRM over HTTP")

	vmutils.ConfigureWinRMOverHTTPS(role, "")
	log.Debug("Configured WinRM over HTTPS without using a thumbprint")

	// Attach VM to a specific subnet
	if d.Subnet != "" {
		err = vmutils.ConfigureWithSubnet(role, d.Subnet)
		if err != nil {
			log.Error("failed to configure subnet:", d.Subnet, ", err:", err)
			return err
		}
		log.Debug("subnet is:", d.Subnet)
	}

	return nil
}