示例#1
0
//
// getClient returns a client for Azure API endpoint. Requires the
// publishsettings file to be already specified to the driver
//
// Parameters:
//   None
// Returns:
//   management.Client: client object to Azure API endpoint
//   error: errors from establishing new client
//
func (d *Driver) getClient() (management.Client, error) {
	client, err := management.ClientFromPublishSettingsFile(d.PublishSettingsFilePath, "")
	if err != nil {
		return management.NewAnonymousClient(), err
	}
	return client, nil
}
示例#2
0
文件: config.go 项目: rgl/terraform
// 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
}
示例#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)
	}
}
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)
	}
}
示例#5
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)
	}
}
示例#6
0
// Run executes a Packer build and returns a packer.Artifact representing
// a Azure VM image.
func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) {
	ui.Say("Preparing builder...")

	ui.Message("Creating Azure Service Management client...")
	subscriptionID, err := findSubscriptionID(b.config.PublishSettingsPath, b.config.SubscriptionName)
	if err != nil {
		return nil, fmt.Errorf("Error creating new Azure client: %v", err)
	}
	b.client, err = management.ClientFromPublishSettingsFile(b.config.PublishSettingsPath, subscriptionID)
	if err != nil {
		return nil, fmt.Errorf("Error creating new Azure client: %v", err)
	}

	// add logger if appropriate
	b.client = GetLoggedClient(b.client)

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

	// complete flags
	state.Put(constants.SrvExists, 0)
	state.Put(constants.CertInstalled, 0)
	state.Put(constants.CertUploaded, 0)
	state.Put(constants.VmExists, 0)
	state.Put(constants.DiskExists, 0)
	state.Put(constants.VmRunning, 0)
	state.Put(constants.ImageCreated, 0)

	var steps []multistep.Step

	if b.config.OSType == constants.Target_Linux {
		steps = []multistep.Step{
			&lin.StepCreateCert{
				TmpServiceName: b.config.tmpServiceName,
			},
			new(StepValidate),
			&StepCreateService{
				Location:       b.config.Location,
				TmpServiceName: b.config.tmpServiceName,
			},
			&StepUploadCertificate{
				TmpServiceName: b.config.tmpServiceName,
			},
			new(StepCreateVm),
			&StepPollStatus{
				TmpServiceName: b.config.tmpServiceName,
				TmpVmName:      b.config.tmpVmName,
				OSType:         b.config.OSType,
			},

			&communicator.StepConnectSSH{
				Config:    &b.config.Comm,
				Host:      lin.SSHHost,
				SSHConfig: lin.SSHConfig(b.config.UserName),
			},
			&common.StepProvision{},

			&lin.StepGeneralizeOS{
				Command: "sudo /usr/sbin/waagent -force -deprovision+user && export HISTSIZE=0 && sync",
			},
			&StepStopVm{
				TmpVmName:      b.config.tmpVmName,
				TmpServiceName: b.config.tmpServiceName,
			},
			&StepCreateImage{
				TmpServiceName:    b.config.tmpServiceName,
				TmpVmName:         b.config.tmpVmName,
				UserImageName:     b.config.userImageName,
				UserImageLabel:    b.config.UserImageLabel,
				RecommendedVMSize: b.config.InstanceSize,
			},
		}
	} else if b.config.OSType == constants.Target_Windows {
		steps = []multistep.Step{
			new(StepValidate),
			&StepCreateService{
				Location:       b.config.Location,
				TmpServiceName: b.config.tmpServiceName,
			},
			new(StepCreateVm),
			&StepPollStatus{
				TmpServiceName: b.config.tmpServiceName,
				TmpVmName:      b.config.tmpVmName,
				OSType:         b.config.OSType,
			},
			&win.StepSetProvisionInfrastructure{
				VmName:                    b.config.tmpVmName,
				ServiceName:               b.config.tmpServiceName,
				StorageAccountName:        b.config.StorageAccount,
				TempContainerName:         b.config.tmpContainerName,
				ProvisionTimeoutInMinutes: b.config.ProvisionTimeoutInMinutes,
			},
			&common.StepProvision{},
			&StepStopVm{
				TmpVmName:      b.config.tmpVmName,
				TmpServiceName: b.config.tmpServiceName,
			},
			&StepCreateImage{
				TmpServiceName:    b.config.tmpServiceName,
				TmpVmName:         b.config.tmpVmName,
				UserImageName:     b.config.userImageName,
				UserImageLabel:    b.config.UserImageLabel,
				RecommendedVMSize: b.config.InstanceSize,
			},
		}

	} else {
		return nil, fmt.Errorf("Unkonwn OS type: %s", b.config.OSType)
	}

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

	// Report any errors.
	if rawErr, ok := state.GetOk("error"); ok {
		return nil, rawErr.(error)
	}

	// If we were interrupted or cancelled, then just exit.
	if _, ok := state.GetOk(multistep.StateCancelled); ok {
		return nil, errors.New("Build was cancelled.")
	}

	if _, ok := state.GetOk(multistep.StateHalted); ok {
		return nil, errors.New("Build was halted.")
	}

	vmImageList, err := vmimage.NewClient(b.client).ListVirtualMachineImages(
		vmimage.ListParameters{
			Location: b.config.Location,
		})
	if err != nil {
		log.Printf("VM image client returned error: %s", err)
		return nil, fmt.Errorf("Can't create artifact")
	}

	if userImage, found := FindVmImage(vmImageList.VMImages, b.config.userImageName, b.config.UserImageLabel); found {
		return &artifact{
			imageLabel:    userImage.Label,
			imageName:     userImage.Name,
			mediaLocation: userImage.OSDiskConfiguration.MediaLink,

			publishSettingsPath: b.config.PublishSettingsPath,
			subscriptionID:      subscriptionID,
		}, nil
	} else {
		log.Printf("could not find image %s", b.config.userImageName)
		return nil, fmt.Errorf("Can't create artifact")
	}
}
示例#7
0
func (p *PostProcessor) PostProcess(ui packer.Ui, artifact packer.Artifact) (packer.Artifact /*keep*/, bool, error) {
	ui.Say("Validating artifact")
	if artifact.BuilderId() != azure.BuilderId {
		return nil, false, fmt.Errorf(
			"Unknown artifact type: %s\nCan only import from Azure builder artifacts (%s).",
			artifact.BuilderId(), azure.BuilderId)
	}

	publishSettingsPath, ok := artifact.State("publishSettingsPath").(string)
	if !ok || publishSettingsPath == "" {
		return nil, false, fmt.Errorf(stateError, "publishSettingsPath")
	}
	subscriptionID, ok := artifact.State("subscriptionID").(string)
	if !ok || subscriptionID == "" {
		return nil, false, fmt.Errorf(stateError, "subscriptionID")
	}

	name := artifact.Id()

	ui.Message("Creating Azure Service Management client...")
	client, err := management.ClientFromPublishSettingsFile(publishSettingsPath, subscriptionID)
	if err != nil {
		return nil, false, fmt.Errorf("Error creating new Azure client: %v", err)
	}
	client = azure.GetLoggedClient(client)
	vmic := virtualmachineimage.NewClient(client)

	ui.Message("Retrieving VM image...")
	var image virtualmachineimage.VMImage
	if err = retry.ExecuteOperation(func() error {
		imageList, err := vmic.ListVirtualMachineImages(
			virtualmachineimage.ListParameters{
				Category: virtualmachineimage.CategoryUser,
			})
		if err != nil {
			return err
		}

		for _, i := range imageList.VMImages {
			if i.Name == name {
				image = i
				break
			}
		}
		return nil
	}); err != nil {
		log.Printf("VM image client returned error: %s", err)
		return nil, false, err
	}
	if image.Name != name {
		return nil, false, fmt.Errorf("Could not find image: %s", name)
	}

	ui.Message(fmt.Sprintf("Deleting VM image (keeping VHDs) %s: %s...", image.Name, image.Label))
	err = retry.ExecuteOperation(func() error { return vmic.DeleteVirtualMachineImage(image.Name, false) })
	if err != nil {
		log.Printf("Error deleting VM image: %s", err)
		return nil, false, err
	}

	blobs := VMBlobListArtifact{
		OSDisk:    image.OSDiskConfiguration.MediaLink,
		DataDisks: make([]string, len(image.DataDiskConfigurations))}

	for i, ddc := range image.DataDiskConfigurations {
		blobs.DataDisks[i] = ddc.MediaLink
	}

	return blobs, false, nil
}