之前发的blog简单的介绍了如何使用Management Class Libraries 来控制Azure platform。

但由于官方并没有提供文档,所以我们只能够通过自己研究来摸索使用该类库的方法。

在使用过程中我发现可以再抽象出一层中间层,从而让该类库的使用更趋近于Management REST API。

下面以创建一个Virtual Machine 为例让我们来了解如何使用该类库来操作Virtual Machine

首先我们要知道,在Azure Platform中,任何一个VM Instance都要运行在一个HostedService 里面的Deployment下面的。

所以在使用过程中我们需要首先创建一个Hosted Service。

我们可以通过以下两个方法来进行创建:

  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。

第一种:首先创建一个Deployment,然后再通过添加角色来向这个Deployment中添加Virtual Machine,这样需要与Azure平台交互两次。

第二种:直接调用创建虚拟机部署,这样将在一个Request中创建一个虚拟机的Deployment并且将添加1或多个Virtual Machine到该Deployment下面。

我们可以通过创建自己的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 = , Name = "RDP", Protocol = "tcp" },
                    new InputEndpoint { LocalPort = , Port = , 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)));
} }

Azure Virtual Machine 之 如何利用Management Class Libraries 创建VM的更多相关文章

  1. Windows Azure Virtual Machine (29) 修改Azure VM 数据磁盘容量

    <Windows Azure Platform 系列文章目录> 当我们使用Windows Azure管理界面,创建Azure虚拟机的时候,默认挂载的磁盘是固定大小的 1.比如我创建1个Wi ...

  2. [New Portal]Windows Azure Virtual Machine (23) 使用Storage Space,提高Virtual Machine磁盘的IOPS

    <Windows Azure Platform 系列文章目录> 注意:如果使用Azure Virtual Machine,虚拟机所在的存储账号建议使用Local Redundant.不建议 ...

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

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

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

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

  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. MySQL模糊查询

    第一种最土的方法:使用like语句第二种用全文索引 有两种方法,第一种最土的方法:使用like语句第二种听涛哥说用全文索引,就在网上搜一下: 如何在MySQL中获得更好的全文搜索结果 mysql针对这 ...

  2. Canvas实现文字散粒子化

    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  3. linux常用命令(一)

    1.linux文件命名规则 1.除了/之外,所有字符都是可以用的. 2.有些字符最好别用,如空格,制表符,退格,@#&-,命令行操作时候可能会出现混淆. 3.避免使用.作为文件开头,linux ...

  4. javascript中矩形的碰撞检测---- 计算碰撞部分的面积

    今天在做一个拖拽改变元素排序的东西的时候,在做被拖动元素同时碰撞到两个元素时,究竟应该与哪个元素交换位置的问题上,纠结到崩溃,实在是想不到别的办法去做了,只能去想办法计算碰撞的面积. 这应该不是最合适 ...

  5. js 中将日期转换为星期需要注意的

    new Date(strDate); 中strDate需要是1998/10/30这样的格式,如果是1998-10-30的格式,不一定旧版本的web能兼容

  6. 如何解决Visual Studio调试Debug很卡很慢

    http://brightguo.com/make-debugging-faster-with-visual-studio/ Have you ever been frustrated by slow ...

  7. SEO

    白帽SEO 内容优化 网站标题.关键字.描述 网站内容优化 Robot.txt文件 网站地图 增加外链引用 2. 网站结构布局优化 网站加载速度:一个页面<100k 扁平化:网站 目录层次 少, ...

  8. C++ 环形缓冲区的实现

    参考文章:http://blog.csdn.net/linyt/article/details/53355355 本文参考linux系统中 kfifo缓冲区实现.由于没有涉及到锁,在多线程环境下,只适 ...

  9. JQ first-child与:first的区别以及nth-child(index)与eq(index)的区别

    1.first-child和:first区别 first-child  是指选取每个父元素的第一个子元素 如$("div:first-child")指每个父级里的第一个div孩子 ...

  10. golang: 常用数据类型底层结构分析

    虽然golang是用C实现的,并且被称为下一代的C语言,但是golang跟C的差别还是很大的.它定义了一套很丰富的数据类型及数据结构,这些类型和结构或者是直接映射为C的数据类型,或者是用C struc ...