Windows Azure Management Librairies : Création d’un compte de stockage, d’un cloud Service et déploiement de la machine virtuelle (2/2)
Dans l’article précédent, nous avons vu comment créer un certificat et s’authentifier pour utiliser le SDK WAML.
La première étape importante pour créer une machine virtuelle avec ce SDK est la création d’un espace de stockage Azure (« Azure Storage » qui servira à stocker les disques virtuels (.vhd) de notre machine virtuelle sous forme de blobs. Ce storage Azure doit posséder un nom unique et doit être créé dans une région proposée par Azure.
Au sein de ce Storage Azure, il est nécessaire de créer un conteneur qui aura pour rôle comme son nom l’indique de « contenir » nos blobs :
// Steps to create a storage account with a container using (ManagementClient managerClient = CloudContext.Clients.CreateManagementClient(azureCredentials)) { using (StorageManagementClient storageClient = CloudContext.Clients.CreateStorageManagementClient(azureCredentials)) { string storageName = "storagedemoiswaml"; // The storage name must be in lower case string accountype = "Standard_LRS"; // 1 Get the location for the storage account LocationsListResponse regionsResponse = await managerClient.Locations.ListAsync(); string region = regionsResponse.Locations.FirstOrDefault(r => r.Name == "North Europe").Name; // 2. Check if the storage account name is available CheckNameAvailabilityResponse nameAvailibility = await storageClient.StorageAccounts.CheckNameAvailabilityAsync(storageName); if (!nameAvailibility.IsAvailable) { Console.WriteLine(string.Format("A storage account named {0} already exists", storageName)); } // Create the storage OperationStatusResponse response = await storageClient.StorageAccounts.CreateAsync(new StorageAccountCreateParameters() { AccountType = accountype, Location = region, Name = storageName }); if (response.Status == OperationStatus.Succeeded) { string containerName = "virtualmachines"; // Get the blob storage connexion string var keys = await storageClient.StorageAccounts.GetKeysAsync(storageName); string storageConnexionString = string.Format(CultureInfo.InvariantCulture, "DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", storageName, keys.SecondaryKey); // Create a container within the blob storage var blobClient = CloudStorageAccount.Parse(storageConnexionString).CreateCloudBlobClient(); var container = blobClient.GetContainerReference(containerName); bool containerIsCreated = await container.CreateIfNotExistsAsync(); if (containerIsCreated) { await container.SetPermissionsAsync(new BlobContainerPermissions() { PublicAccess = BlobContainerPublicAccessType.Container }); } else { Console.WriteLine(string.Format("An error occured during the container create operation in the storage {0}", storageName)); } Console.WriteLine(string.Format("The blob storage {0} was created sucessfully. Uri : {1}", storageName, storageConnexionString)); } else { Console.WriteLine("An error occured during the storage account create operation."); } } }
La seconde étape obligatoire avant de créer notre machine virtuelle est de créer l’environnement d’exécution de notre vm : un « Cloud Service Azure ». Ce cloud service va fournir la RAM, les ressources processeurs et un nom de domaine qui nous permettra d’accéder à la vm. Le cloud service doit être créé dans la même région que le compte de stockage précédent et doit posséder un nom unique :
using (ManagementClient managerClient = CloudContext.Clients.CreateManagementClient(azureCredentials)) { // Create the Cloud service wich will host the vm using (ComputeManagementClient _computeClient = CloudContext.Clients.CreateComputeManagementClient(azureCredentials)) { serviceName = "myDemoCloudServiceIsWaml"; LocationsListResponse regionsResponse = await managerClient.Locations.ListAsync(); string region = regionsResponse.Locations.FirstOrDefault(r => r.Name == "North Europe").Name; HostedServiceCheckNameAvailabilityResponse serviceNameAvailibility = await _computeClient.HostedServices.CheckNameAvailabilityAsync(serviceName); if (!serviceNameAvailibility.IsAvailable) { Console.WriteLine(string.Format("A cloud service named {0} already exists", serviceName)); } OperationResponse response = await _computeClient.HostedServices.CreateAsync(new HostedServiceCreateParameters { ServiceName = serviceName, Location = region }); if (response.StatusCode == System.Net.HttpStatusCode.Created) { Console.WriteLine(string.Format("The cloud service named {0} was created successfully", serviceName)); } } }
Maintenant, en se connectant sur le portail Azure, nous possédons deux nouvelles ressources :
Un espace de stockage :
Ainsi qu’un cloud service :
Notre cloud service ne possède cependant aucun déploiement, la dernière étape consiste donc à provisionner notre cloud service avec une instance de machine virtuelle
Pour créer et deployer notre vm, plusieurs étapes sont à nouveau nécessaires :
- configuration du disque dur virtuel et de l’OS de notre future vm
- configuration réseau pour accéder à notre vm (en RDP ou via PowerShell par exemple)
- création du déploiement
- création d’un rôle
- création et ajout d’une instance de la vm au sein du role
using (ComputeManagementClient _computeClient = CloudContext.Clients.CreateComputeManagementClient(azureCredentials)) { // Os images (.vhd OS disk) var osImages = await _computeClient.VirtualMachineOSImages.ListAsync(); // Windows 10 os Image VirtualMachineOSImageListResponse.VirtualMachineOSImage osImage = osImages.FirstOrDefault( os => os.OperatingSystemType == "Windows" && os.Label.Contains("Windows 10 Enterprise (x64)")); string osDiskUniqueName = osImage.Name + "_disk"; // OS virtual disk configuration OSVirtualHardDisk OsVirtualDisk = new OSVirtualHardDisk() { Label = osImage.Label, MediaLink = new Uri(string.Format("{0}/{1}", _containerUri, osDiskUniqueName + ".vhd"), UriKind.Absolute), Name = osDiskUniqueName, // The disk Name must be unique OperatingSystem = osImage.OperatingSystemType, SourceImageName = osImage.Name }; // OS configuration ConfigurationSet osConfigSet = new ConfigurationSet() { ConfigurationSetType = ConfigurationSetTypes.WindowsProvisioningConfiguration, AdminUserName = "thibaut", AdminPassword = "azerty@infiniteSquare25", ComputerName = "myVm" }; // Network configuration with endpoints definition List<InputEndpoint> endpoints = new List<InputEndpoint>(); endpoints.Add(new InputEndpoint() { Name = "Remote Desktop", Port = 51299, Protocol = "TCP", LocalPort = 3389 }); endpoints.Add(new InputEndpoint() { Name = "PowerShell", Port = 5986, Protocol = "TCP", LocalPort = 5986 }); ConfigurationSet netWorkSet = new ConfigurationSet() { ConfigurationSetType = ConfigurationSetTypes.NetworkConfiguration, InputEndpoints = endpoints, AdminUserName = "ImTheNetworkAdmin", AdminPassword = "thisIsMyPassw@rd15" }; // Collection of configurations for the deploymement List<ConfigurationSet> configurations = new List<ConfigurationSet>() { osConfigSet, netWorkSet }; // Select a size for the role var smallSize = (await managerClient.RoleSizes.ListAsync()).FirstOrDefault(s => s.Name == "Basic_A0"); string deploymentName = "deployIsDemoVmWaml"; // Deployment params VirtualMachineCreateDeploymentParameters vmdeploymentParams = new VirtualMachineCreateDeploymentParameters() { DeploymentSlot = DeploymentSlot.Production, Label = deploymentName, Name = deploymentName }; Role role = new Role() { RoleType = VirtualMachineRoleType.PersistentVMRole.ToString(), RoleName = "IsDemoVmWaml", OSVirtualHardDisk = OsVirtualDisk, ConfigurationSets = configurations, RoleSize = smallSize.Name, ProvisionGuestAgent = true }; vmdeploymentParams.Roles.Add(role); try { var deploymentResult = await _computeClient.VirtualMachines.CreateDeploymentAsync(serviceName, vmdeploymentParams); if (deploymentResult.Status != OperationStatus.Succeeded) { Console.WriteLine(string.Format("An error occured during the virtual machine deployment operation. Error message : {0}", deploymentResult.Error.Message)); } else { Console.WriteLine(string.Format("The virtual machine named was created successfully. It's disponible from the following url : {0} ", string.Format("http://{0}.cloudapp.net", serviceName))); } } catch (Exception e) { Console.WriteLine(string.Format("An error occured during the virtual machine create operation. Error message : {0}", e.Message)); } } }
Happy coding
Commentaires