咱們在不少時候可能會須要用程序來控制VM的建立,刪除工做。web
而在這些工做之中,用程序建立一個VM將會是一個很是複雜的過程,由於他涉及到不少步驟。windows
具體步驟以下tcp
1 建立一個Hosted cloud serviceui
2 選中一個Azure 中的image 來建立對應的VHDspa
3 選擇一個路徑來存放這個建立的VHD.net
4 選擇這個VM須要開放的端口,須要遠程登陸的帳號密碼等等配置信息。code
5 建立一個帶有若干個虛擬機的部署。orm
若是想用代碼來實現的話,如今有兩種方式blog
1 用REST APIip
2 用Management Class Library
REST API的方法,網上已經有了(詳情可參考 http://www.codeproject.com/Articles/601419/How-to-manage-Azure-IaaS-Programmatically )
這裏就只講述 第二種方式,用 Management Class Libraries。
如下是建立Azure VM 的代碼。
public static void QuickCreateVM() { try { ComputeManagementClient client = new ComputeManagementClient(cloudCredentials); string vmName = "yuan2013vm"; //STEP1:Create Hosted Service //Azure VM must be hosted in a hosted cloud service. createCloudService(vmName, "East Asia", null); //STEP2:Construct VM Role instance var vmRole = new Role() { RoleType = VirtualMachineRoleType.PersistentVMRole.ToString(), RoleName = vmName, Label = vmName, RoleSize = VirtualMachineRoleSize.Small, ConfigurationSets = new List<ConfigurationSet>(), OSVirtualHardDisk = new OSVirtualHardDisk() { MediaLink = getVhdUri(string.Format("{0}.blob.core.windows.net/vhds", relatedStorageAccountName)), SourceImageName = GetSourceImageNameByFamliyName("Windows Server 2012 Datacenter") } }; ConfigurationSet configSet = new ConfigurationSet { ConfigurationSetType = ConfigurationSetTypes.WindowsProvisioningConfiguration, EnableAutomaticUpdates = true, ResetPasswordOnFirstLogon = false, ComputerName = vmName, AdminUserName = "UserName", AdminPassword = "Password1!", 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); vmRole.ResourceExtensionReferences = null; //STEP3: Add Role instance to Deployment Parmeters List<Role> roleList = new List<Role>() { vmRole }; VirtualMachineCreateDeploymentParameters createDeploymentParams = new VirtualMachineCreateDeploymentParameters { Name = vmName, Label = vmName, Roles = roleList, DeploymentSlot = DeploymentSlot.Production }; //STEP4: Create a Deployment with VM Roles. client.VirtualMachines.CreateDeployment(vmName, createDeploymentParams); Console.WriteLine("Create VM success"); } catch (CloudException e) { throw e; } catch (Exception ex) { throw ex; } } private static Uri getVhdUri(string blobcontainerAddress) { var now = DateTime.UtcNow; string dateString = now.Year + "-" + now.Month + "-" + now.Day + now.Hour + now.Minute + now.Second + now.Millisecond; var address = string.Format("http://{0}/{1}-650.vhd", blobcontainerAddress, dateString); return new Uri(address); } private static void createCloudService(string cloudServiceName, string location, string affinityGroupName = null) { ComputeManagementClient client = new ComputeManagementClient(cloudCredentials); HostedServiceCreateParameters hostedServiceCreateParams = new HostedServiceCreateParameters(); if (location != null) { hostedServiceCreateParams = new HostedServiceCreateParameters { ServiceName = cloudServiceName, Location = location, Label = EncodeToBase64(cloudServiceName), }; } else if (affinityGroupName != null) { hostedServiceCreateParams = new HostedServiceCreateParameters { ServiceName = cloudServiceName, AffinityGroup = affinityGroupName, Label = EncodeToBase64(cloudServiceName), }; } try { client.HostedServices.Create(hostedServiceCreateParams); } catch (CloudException e) { throw e; } } private static string EncodeToBase64(string toEncode) { byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode); string returnValue = System.Convert.ToBase64String(toEncodeAsBytes); return returnValue; } private static string GetSourceImageNameByFamliyName(string imageFamliyName) { ComputeManagementClient client = new ComputeManagementClient(cloudCredentials); var results = client.VirtualMachineImages.List(); var disk = results.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")); } }
須要注意的問題有幾下幾點
1 "East Asia" 是數據中心的地址,你能夠在portal中建立VM的時候找到相關選項。
2 在建立Azure虛擬機的時候,它的結構與Cloud service 相似,即頂層仍是須要一個hosted service,接着是deployment,虛擬機必須在deployment之中。
3 在 Azure REST API 中有兩個方法來添加虛擬機, Add ROLE和 CreateVMDeployment,常常有人搞不清這兩個的區別,在瞭解第二點之後這裏就很好理解了。
CreateVMDeployment,是先建立一個VM Deployment,而後再向其中添加若干個VM(一般是一個), 而ADD role 必須向已經存在的Deployment中添加VM,並且只能添加一臺。
你能夠從MSDN下載我上傳的代碼文件。
若是以爲有用請給5分好評謝謝。