以前發的blog簡單的介紹瞭如何使用Management Class Libraries 來控制Azure platform。web
但因爲官方並無提供文檔,因此咱們只可以經過本身研究來摸索使用該類庫的方法。
windows
在使用過程當中我發現能夠再抽象出一層中間層,從而讓該類庫的使用更趨近於Management REST API。tcp
下面以建立一個Virtual Machine 爲例讓咱們來了解如何使用該類庫來操做Virtual Machineide
首先咱們要知道,在Azure Platform中,任何一個VM Instance都要運行在一個HostedService 裏面的Deployment下面的。this
因此在使用過程當中咱們須要首先建立一個Hosted Service。spa
咱們能夠經過如下兩個方法來進行建立:.net
public static void createCloudServiceByLocation(string cloudServiceName, string location) { ComputeManagementClient client = new ComputeManagementClient(getCredentials()); HostedServiceCreateParameters hostedServiceCreateParams = new HostedServiceCreateParameters { ServiceName = cloudServiceName, Location = location, Label = EncodeToBase64(cloudServiceName), }; try { client.HostedServices.Create(hostedServiceCreateParams); } catch (CloudException e) { throw e; } } public static void createCloudServiceByAffinityGroup(string cloudServiceName, string affinityGroupName) { ComputeManagementClient client = new ComputeManagementClient(getCredentials()); HostedServiceCreateParameters hostedServiceCreateParams = new HostedServiceCreateParameters { ServiceName = cloudServiceName, AffinityGroup = affinityGroupName, Label = EncodeToBase64(cloudServiceName), }; try { client.HostedServices.Create(hostedServiceCreateParams); } catch (CloudException e) { throw e; } }
在有了HostedService以後,咱們能夠經過兩種方式來建立VM。3d
第一種:首先建立一個Deployment,而後再經過添加角色來向這個Deployment中添加Virtual Machine,這樣須要與Azure平臺交互兩次。code
第二種:直接調用建立虛擬機部署,這樣將在一個Request中建立一個虛擬機的Deployment而且將添加1或多個Virtual Machine到該Deployment下面。orm
咱們能夠經過建立本身的Extension Class Library來使得操做更趨向於REST API,一下是我抽象層的代碼:
public static class MyVirtualMachineExtension { /// <summary> /// Instantiation a new VM Role /// </summary> public static Role CreateVMRole(this IVirtualMachineOperations client, string cloudServiceName, string roleName, VirtualMachineRoleSize roleSize, string userName, string password, OSVirtualHardDisk osVHD) { Role vmRole = new Role { RoleType = VirtualMachineRoleType.PersistentVMRole.ToString(), RoleName = roleName, Label = roleName, RoleSize = roleSize, ConfigurationSets = new List<ConfigurationSet>(), OSVirtualHardDisk = osVHD }; ConfigurationSet configSet = new ConfigurationSet { ConfigurationSetType = ConfigurationSetTypes.WindowsProvisioningConfiguration, EnableAutomaticUpdates = true, ResetPasswordOnFirstLogon = false, ComputerName = roleName, AdminUserName = userName, AdminPassword = password, InputEndpoints = new BindingList<InputEndpoint> { new InputEndpoint { LocalPort = 3389, Name = "RDP", Protocol = "tcp" }, new InputEndpoint { LocalPort = 80, Port = 80, Name = "web", Protocol = "tcp" } } }; vmRole.ConfigurationSets.Add(configSet); return vmRole; } public static OSVirtualHardDisk CreateOSVHD(this IVirtualMachineImageOperations operation, string cloudserviceName, string vmName, string storageAccount, string imageFamiliyName) { try { var osVHD = new OSVirtualHardDisk { MediaLink = GetVhdUri(string.Format("{0}.blob.core.windows.net/vhds", storageAccount), cloudserviceName, vmName), SourceImageName = GetSourceImageNameByFamliyName(operation, imageFamiliyName) }; return osVHD; } catch (CloudException e) { throw e; } } private static string GetSourceImageNameByFamliyName(this IVirtualMachineImageOperations operation, string imageFamliyName) { var disk = operation.List().Where(o => o.ImageFamily == imageFamliyName).FirstOrDefault(); if (disk != null) { return disk.Name; } else { throw new CloudException(string.Format("Can't find {0} OS image in current subscription")); } } private static Uri GetVhdUri(string blobcontainerAddress, string cloudServiceName, string vmName, bool cacheDisk = false, bool https = false) { var now = DateTime.UtcNow; string dateString = now.Year + "-" + now.Month + "-" + now.Day; var address = string.Format("http{0}://{1}/{2}-{3}-{4}-{5}-650.vhd", https ? "s" : string.Empty, blobcontainerAddress, cloudServiceName, vmName, cacheDisk ? "-CacheDisk" : string.Empty, dateString); return new Uri(address); } public static void CreateVMDeployment(this IVirtualMachineOperations operations, string cloudServiceName, string deploymentName, List<Role> roleList, DeploymentSlot slot = DeploymentSlot.Production) { try { VirtualMachineCreateDeploymentParameters createDeploymentParams = new VirtualMachineCreateDeploymentParameters { Name = deploymentName, Label = cloudServiceName, Roles = roleList, DeploymentSlot = slot }; operations.CreateDeployment(cloudServiceName, createDeploymentParams); } catch (CloudException e) { throw e; } } public static void AddRole(this IVirtualMachineOperations operations, string cloudServiceName, string deploymentName, Role role, DeploymentSlot slot = DeploymentSlot.Production) { try { VirtualMachineCreateParameters createParams = new VirtualMachineCreateParameters { RoleName = role.Label, RoleSize = role.RoleSize, OSVirtualHardDisk = role.OSVirtualHardDisk, ConfigurationSets = role.ConfigurationSets, AvailabilitySetName = role.AvailabilitySetName, DataVirtualHardDisks = role.DataVirtualHardDisks }; operations.Create(cloudServiceName, deploymentName, createParams); } catch (CloudException e) { throw e; } } }
總體programe代碼以下:
class Program { public const string base64EncodedCertificate = ""; public const string subscriptionId = ""; public static string vmName = "Azure111"; public static string location = "East Asia"; public static string storageAccountName = "superdino"; public static string userName = "Dino"; public static string password = "PassWord1!"; public static string imageFamiliyName = "Windows Server 2012 Datacenter"; static void Main(string[] args) { ComputeManagementClient client = new ComputeManagementClient(getCredentials()); //You need a hosted service host VM. try { client.HostedServices.Get(vmName); } catch (CloudException e) { createCloudServiceByLocation(vmName, location); } var OSVHD = client.VirtualMachineImages.CreateOSVHD(vmName, vmName, storageAccountName, imageFamiliyName); var VMROle = client.VirtualMachines.CreateVMRole(vmName, vmName, VirtualMachineRoleSize.Small, userName, password, OSVHD); List<Role> roleList = new List<Role>{ VMROle }; client.VirtualMachines.CreateVMDeployment(vmName, vmName, roleList); Console.WriteLine("Create VM success"); client.VirtualMachines.AddRole("CloudServiceName", "ExsitDeploymentName", VMROle); Console.ReadLine(); } public static void createCloudServiceByLocation(string cloudServiceName, string location) { ComputeManagementClient client = new ComputeManagementClient(getCredentials()); HostedServiceCreateParameters hostedServiceCreateParams = new HostedServiceCreateParameters { ServiceName = cloudServiceName, Location = location, Label = EncodeToBase64(cloudServiceName), }; try { client.HostedServices.Create(hostedServiceCreateParams); } catch (CloudException e) { throw e; } } public static void createCloudServiceByAffinityGroup(string cloudServiceName, string affinityGroupName) { ComputeManagementClient client = new ComputeManagementClient(getCredentials()); HostedServiceCreateParameters hostedServiceCreateParams = new HostedServiceCreateParameters { ServiceName = cloudServiceName, AffinityGroup = affinityGroupName, Label = EncodeToBase64(cloudServiceName), }; try { client.HostedServices.Create(hostedServiceCreateParams); } catch (CloudException e) { throw e; } } public static string EncodeToBase64(string toEncode) { byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode); string returnValue = System.Convert.ToBase64String(toEncodeAsBytes); return returnValue; } public static SubscriptionCloudCredentials getCredentials() { return new CertificateCloudCredentials(subscriptionId, new X509Certificate2(Convert.FromBase64String(base64EncodedCertificate))); } }