咱们在不少时候可能会须要用程序来控制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分好评谢谢。