func validateStorageAccount(config *Config, client management.Client) (string, error) { ssc := storageservice.NewClient(client) sa, err := ssc.GetStorageService(config.StorageAccount) if err != nil { return "", err } if sa.StorageServiceProperties.Location != config.Location { return "", fmt.Errorf("Storage Account %q is not in location %q, but in location %q.", config.StorageAccount, sa.StorageServiceProperties.Location, config.Location) } var blobEndpoint string for _, uri := range sa.StorageServiceProperties.Endpoints { if strings.Contains(uri, ".blob.") { blobEndpoint = uri } } if blobEndpoint == "" { return "", fmt.Errorf("Could not find blob endpoint for account %q in %v", sa.ServiceName, sa.StorageServiceProperties.Endpoints) } log.Printf("Blob endpoint: %s", blobEndpoint) return fmt.Sprintf("%s%s/%s.vhd", blobEndpoint, config.StorageContainer, config.tmpVmName), nil }
// 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 uploadBlob(cl ExtensionsClient, storageAccount, packagePath string) (string, error) { // Fetch keys for storage account svc := storageservice.NewClient(cl.client) keys, err := svc.GetStorageServiceKeys(storageAccount) if err != nil { return "", fmt.Errorf("Could not fetch keys for storage account. Make sure it is in publisher subscription. Error: %v", err) } log.Debug("Retrieved storage account keys.") // Read package pkg, err := os.OpenFile(packagePath, os.O_RDONLY, 0777) if err != nil { return "", fmt.Errorf("Could not reach package file: %v", err) } stat, err := pkg.Stat() if err != nil { return "", fmt.Errorf("Could not stat the package file: %v", err) } defer pkg.Close() // Upload blob sc, err := storage.NewBasicClient(storageAccount, keys.PrimaryKey) if err != nil { return "", fmt.Errorf("Could not create storage client: %v", err) } bs := sc.GetBlobService() if _, err := bs.CreateContainerIfNotExists(containerName, storage.ContainerAccessTypeBlob); err != nil { return "", fmt.Errorf("Error creating blob container: %v", err) } blobName := fmt.Sprintf("%d.zip", time.Now().Unix()) if err := bs.CreateBlockBlobFromReader(containerName, blobName, uint64(stat.Size()), pkg, nil); err != nil { return "", fmt.Errorf("Error uploading blob: %v", err) } return bs.GetBlobURL(containerName, blobName), nil }
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 GetTestStorageAccount(t *testing.T, client management.Client) storage.StorageServiceResponse { t.Log("Retrieving storage account") sc := storage.NewClient(client) var sa storage.StorageServiceResponse ssl, err := sc.ListStorageServices() if err != nil { t.Fatal(err) } rnd := rand.New(rand.NewSource(time.Now().UnixNano())) if len(ssl.StorageServices) == 0 { t.Log("No storage accounts found, creating a new one") lc := location.NewClient(client) ll, err := lc.ListLocations() if err != nil { t.Fatal(err) } loc := ll.Locations[rnd.Intn(len(ll.Locations))].Name t.Logf("Location for new storage account: %s", loc) name := GenerateName() op, err := sc.CreateStorageService(storage.StorageAccountCreateParameters{ ServiceName: name, Label: base64.StdEncoding.EncodeToString([]byte(name)), Location: loc, AccountType: storage.AccountTypeStandardLRS}) if err != nil { t.Fatal(err) } if err := client.WaitForOperation(op, nil); err != nil { t.Fatal(err) } sa, err = sc.GetStorageService(name) } else { sa = ssl.StorageServices[rnd.Intn(len(ssl.StorageServices))] } t.Logf("Selected storage account '%s' in location '%s'", sa.ServiceName, sa.StorageServiceProperties.Location) return sa }
func (b *Builder) validateAzureOptions(ui packer.Ui, state *multistep.BasicStateBag) error { var err error // Check Storage account (& container) ui.Message("Checking Storage Account...") availabilityResponse, err := storageservice.NewClient(b.client).CheckStorageAccountNameAvailability(b.config.StorageAccount) if err != nil { return err } if availabilityResponse.Result { return fmt.Errorf("Can't Find Storage Account '%s'", b.config.StorageAccount) } // Check image exists imageList, err := osimage.NewClient(b.client).ListOSImages() if err != nil { log.Printf("OS image client returned error: %s", err) return err } if osImage, found := FindOSImage(imageList.OSImages, b.config.OSImageLabel, b.config.Location); found { state.Put(constants.OSImageName, osImage.Name) state.Put(constants.IsOSImage, true) return nil } else { imageList, err := vmimage.NewClient(b.client).ListVirtualMachineImages() if err != nil { log.Printf("VM image client returned error: %s", err) return err } if vmImage, found := FindVmImage(imageList.VMImages, "", b.config.OSImageLabel, b.config.Location); found { state.Put(constants.OSImageName, vmImage.Name) state.Put(constants.IsOSImage, false) return nil } else { return fmt.Errorf("Can't find VM or OS image '%s' Located at '%s'", b.config.OSImageLabel, b.config.Location) } } }
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 }
func validateStorageAccount(config *Config, client management.Client) (string, error) { ssc := storageservice.NewClient(client) sa, err := ssc.GetStorageService(config.StorageAccount) if err != nil { return "", err } if sa.StorageServiceProperties.Location != config.Location { return "", fmt.Errorf("Storage Account %q is not in location %q, but in location %q.", config.StorageAccount, sa.StorageServiceProperties.Location, config.Location) } var blobEndpoint string for _, uri := range sa.StorageServiceProperties.Endpoints { if strings.Contains(uri, ".blob.") { blobEndpoint = uri } } if blobEndpoint == "" { return "", fmt.Errorf("Could not find blob endpoint for account %q in %v", sa.ServiceName, sa.StorageServiceProperties.Endpoints) } log.Printf("Blob endpoint: %s", blobEndpoint) log.Print("Getting key for storage account...") keys, err := ssc.GetStorageServiceKeys(config.StorageAccount) if err != nil { return "", fmt.Errorf("Could not retrieve key for storage account %q", config.StorageAccount) } config.storageAccountKey = keys.PrimaryKey config.storageClient, err = storage.NewClient(config.StorageAccount, config.storageAccountKey, strings.TrimSuffix(blobEndpoint[strings.Index(blobEndpoint, ".blob.")+6:], "/"), storage.DefaultAPIVersion, true) if err != nil { return "", fmt.Errorf("Could not create storage client for account %q", config.StorageAccount) } return fmt.Sprintf("%s%s/%s.vhd", blobEndpoint, config.StorageContainer, config.tmpVmName), nil }
func (s *StepSetProvisionInfrastructure) Run(state multistep.StateBag) multistep.StepAction { ui := state.Get("ui").(packer.Ui) client := state.Get(constants.RequestManager).(management.Client) errorMsg := "Error StepRemoteSession: %s" ui.Say("Preparing infrastructure for provision...") // get key for storage account ui.Message("Getting key for storage account...") keys, err := storageservice.NewClient(client).GetStorageServiceKeys(s.StorageAccountName) if err != nil { err := fmt.Errorf(errorMsg, err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } //create storage driver s.storageClient, err = storage.NewBasicClient(s.StorageAccountName, keys.PrimaryKey) if err != nil { err := fmt.Errorf(errorMsg, err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } //create temporary container s.flagTempContainerCreated = false ui.Message("Creating Azure temporary container...") err = s.storageClient.GetBlobService().CreateContainer(s.TempContainerName, storage.ContainerAccessTypePrivate) if err != nil { err := fmt.Errorf(errorMsg, err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } s.flagTempContainerCreated = true isOSImage := state.Get(constants.IsOSImage).(bool) comm, err := azureVmCustomScriptExtension.New( azureVmCustomScriptExtension.Config{ ServiceName: s.ServiceName, VmName: s.VmName, StorageAccountName: s.StorageAccountName, StorageAccountKey: keys.PrimaryKey, ContainerName: s.TempContainerName, Ui: ui, IsOSImage: isOSImage, ManagementClient: client, }) if err != nil { err := fmt.Errorf(errorMsg, err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } packerCommunicator := packer.Communicator(comm) state.Put("communicator", packerCommunicator) return multistep.ActionContinue }