我们在很多时候可能会需要用程序来控制VM的创建,删除工作。

而在这些工作之中,用程序创建一个VM将会是一个非常复杂的过程,因为他涉及到很多步骤。

具体步骤如下

1 创建一个Hosted cloud service

2 选中一个Azure 中的image 来创建对应的VHD

3 选择一个路径来存放这个创建的VHD

4 选择这个VM需要开放的端口,需要远程登录的账号密码等等配置信息。

5 创建一个带有若干个虚拟机的部署。

如果想用代码来实现的话,现在有两种方式

1 用REST API

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 = , Name = "RDP", Protocol = "tcp" },
new InputEndpoint { LocalPort = , Port = , 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分好评谢谢。

Windows Azure Virtual Machine 之用程序控制Azure VM的更多相关文章

  1. [New Portal]Windows Azure Virtual Machine (11) 在本地使用Hyper-V制作虚拟机模板,并上传至Azure (1)

    <Windows Azure Platform 系列文章目录> 本章介绍的内容是将本地Hyper-V的VHD,上传到Azure数据中心,作为自定义的虚拟机模板. 注意:因为在制作VHD的最 ...

  2. [New Portal]Windows Azure Virtual Machine (12) 在本地使用Hyper-V制作虚拟机模板,并上传至Azure (2)

    <Windows Azure Platform 系列文章目录> 本章介绍的内容是将本地Hyper-V的VHD,上传到Azure数据中心,作为自定义的虚拟机模板. 注意:因为在制作VHD的最 ...

  3. [New Portal]Windows Azure Virtual Machine (13) 在本地使用Hyper-V制作虚拟机模板,并上传至Azure (3)

    <Windows Azure Platform 系列文章目录> 本章介绍的内容是将本地Hyper-V的VHD,上传到Azure数据中心,作为自定义的虚拟机模板. 注意:因为在制作VHD的最 ...

  4. [New Portal]Windows Azure Virtual Machine (14) 在本地制作数据文件VHD并上传至Azure(1)

    <Windows Azure Platform 系列文章目录> 之前的内容里,我介绍了如何将本地的Server 2012中文版 VHD上传至Windows Azure,并创建基于该Serv ...

  5. [New Portal]Windows Azure Virtual Machine (15) 在本地制作数据文件VHD并上传至Azure(2)

    <Windows Azure Platform 系列文章目录> 在上一章内容里,我们已经将包含有OFFICE2013 ISO安装文件的VHD上传至Azure Blob Storage中了. ...

  6. [New Portal]Windows Azure Virtual Machine (16) 使用Azure PowerShell创建Azure Virtual Machine

    <Windows Azure Platform 系列文章目录> 注:本章内容和之前的[New Portal]Windows Azure Virtual Machine (12) 在本地制作 ...

  7. [New Portal]Windows Azure Virtual Machine (18) Azure Virtual Machine内部IP和外部IP

    <Windows Azure Platform 系列文章目录> 在开始本章内容之前,请读者熟悉以下2篇博文:       [New Portal]Windows Azure Virtual ...

  8. [New Portal]Windows Azure Virtual Machine (19) 关闭Azure Virtual Machine与VIP Address,Internal IP Address的关系(1)

    <Windows Azure Platform 系列文章目录> 默认情况下,通过Azure Management Portal创建的Public IP和Private IP都是随机分配的. ...

  9. [New Portal]Windows Azure Virtual Machine (20) 关闭Azure Virtual Machine与VIP Address,Internal IP Address的关系(2)

    <Windows Azure Platform 系列文章目录> 默认情况下,通过Azure Management Portal创建的Public IP和Private IP都是随机分配的. ...

随机推荐

  1. jQuery实现的简单小功能(实用)

    1.返回顶部使用JQuery的animate和scrollTop方法可以创建简单地返回顶部的动画: // Back to top $('#top').click(function (e) { e.pr ...

  2. 20145205 实验一 Java开发环境的熟悉

    实验内容 命令行下Java程序开发 IDEA下Java程序开发.调试 练习(通过命令行和Eclipse两种方式实现,在Eclipse下练习调试程序) 实现凯撒密码,并进行测试 实验要求 使用JDK编译 ...

  3. Android开发使用TotalControl调试遇到的问题(备注)

    背景:Android开发,使用TotalControl控制手机进行调试. 过程:Eclipse调试一直正常,某天下午突然提示:无法启动ADB.exe,请确认是否在对应的路径下. 怀疑是自己程序写的有问 ...

  4. 阿里云服务器Linux CentOS安装配置(零)目录

    阿里云服务器Linux CentOS安装配置(零)目录 阿里云服务器Linux CentOS安装配置(一)购买阿里云服务器 阿里云服务器Linux CentOS安装配置(二)yum安装svn 阿里云服 ...

  5. 合同主体列表添加两条合同主体,返回合并支付页面,支付总弹"请选择合同主体",删除后,竟然还能支付(改合并支付页面的字段状态)

    bug描述: 操作步骤:1.进入"商标续展"产品详情页面,点击立即购买(数量设为2),进入合并订单界面,选择合同主体,点击全部,清空所有合同主体2.新建合同主体保存,设置该合同主体 ...

  6. SQL INSERT INTO 语句

    SQL Order By SQL update INSERT INTO 语句 INSERT INTO 语句用于向表格中插入新的行. 语法 INSERT INTO 表名称 VALUES (值1, 值2, ...

  7. Android新组件CardView

    Android L以后,新增了一个CardView组件,Google官方应用中有不少地方是使用卡片来展示信息,背后应该就是这个CardView. 使用CardView要引入单独的support包:co ...

  8. 转:linux下jar命令与jar包

    原文链接:http://blog.chinaunix.net/uid-692788-id-2681136.htmlJAR包是Java中所特有一种压缩文档,其实大家就可以把它理解为.zip包.当然也是有 ...

  9. ubifs概述

    UBIFS无排序区块图像文件系统(Unsorted Block Image File System, UBIFS)是用于固态存储设备上,并与LogFS相互竞争,作为JFFS2的后继文件系统之一.真正开 ...

  10. Warning C4819

    VC工程里有个文件,只有文件里写了汉字,就报警告C4819 Warning C4819:The file contains a character that can ot be represented ...