Azure Virtual Machine 之 如何利用Management Class Libraries 创建VM
之前发的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的更多相关文章
- Windows Azure Virtual Machine (29) 修改Azure VM 数据磁盘容量
<Windows Azure Platform 系列文章目录> 当我们使用Windows Azure管理界面,创建Azure虚拟机的时候,默认挂载的磁盘是固定大小的 1.比如我创建1个Wi ...
- [New Portal]Windows Azure Virtual Machine (23) 使用Storage Space,提高Virtual Machine磁盘的IOPS
<Windows Azure Platform 系列文章目录> 注意:如果使用Azure Virtual Machine,虚拟机所在的存储账号建议使用Local Redundant.不建议 ...
- [New Portal]Windows Azure Virtual Machine (12) 在本地使用Hyper-V制作虚拟机模板,并上传至Azure (2)
<Windows Azure Platform 系列文章目录> 本章介绍的内容是将本地Hyper-V的VHD,上传到Azure数据中心,作为自定义的虚拟机模板. 注意:因为在制作VHD的最 ...
- [New Portal]Windows Azure Virtual Machine (13) 在本地使用Hyper-V制作虚拟机模板,并上传至Azure (3)
<Windows Azure Platform 系列文章目录> 本章介绍的内容是将本地Hyper-V的VHD,上传到Azure数据中心,作为自定义的虚拟机模板. 注意:因为在制作VHD的最 ...
- [New Portal]Windows Azure Virtual Machine (15) 在本地制作数据文件VHD并上传至Azure(2)
<Windows Azure Platform 系列文章目录> 在上一章内容里,我们已经将包含有OFFICE2013 ISO安装文件的VHD上传至Azure Blob Storage中了. ...
- [New Portal]Windows Azure Virtual Machine (16) 使用Azure PowerShell创建Azure Virtual Machine
<Windows Azure Platform 系列文章目录> 注:本章内容和之前的[New Portal]Windows Azure Virtual Machine (12) 在本地制作 ...
- [New Portal]Windows Azure Virtual Machine (18) Azure Virtual Machine内部IP和外部IP
<Windows Azure Platform 系列文章目录> 在开始本章内容之前,请读者熟悉以下2篇博文: [New Portal]Windows Azure Virtual ...
- [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都是随机分配的. ...
- [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都是随机分配的. ...
随机推荐
- linux常用命令(四)
1.压缩解压命令 gzip命令 默认为.gz格式文件 1.只能压缩文件不可压缩目录 2.不保留源文件 压缩 giz 解压 gunip tar命令 -c产生打包文件 -v显示相信打包压缩过程 - ...
- 如何获取google地图、baidu百度地图的坐标
google:打开google地图-->查找目的地-->右键:此位置居中-->地址栏键入javascript:void(prompt('',gApplication.getMap() ...
- amCharts图表组件
amCharts提供了JavaScript/HTML5 Charts.Javascript/HTML5 Stock Chart.JavaScript Maps三种图表组件.amCharts图形效果炫丽 ...
- Xamarin.Android 应用程序配置
* 在 Xamarin 中 Android 清单文件的内容一般不通过手动编辑,而是由编译器根据 项目属性设置 和 一系列 特性类 自动生成 1. 应用程序在android启动器中显示的名称设置: 主活 ...
- windows 系统时钟
偶然发现了一个函数用以查询操作系统的时钟间隔: BOOL WINAPI GetSystemTimeAdjustment( _Out_ PDWORD lpTimeAdjustment, _Out_ PD ...
- JQ first-child与:first的区别以及nth-child(index)与eq(index)的区别
1.first-child和:first区别 first-child 是指选取每个父元素的第一个子元素 如$("div:first-child")指每个父级里的第一个div孩子 ...
- GridView实现方块布局
效果如下: 先创建一个BaseViewHolder package com.example.griddemo; import android.util.SparseArray; import andr ...
- iOS 导航栏返回的相关跳转
导航条跳转页面的考虑 对于用navigationcontroller来跳转页面的时候,其实是执行堆栈的进栈和出栈的操作,要想释放内存,那么在来回跳转的时候,就要考虑几个问题了 1 A =>B=& ...
- JSONModel对架构的影响及解决方案
越来越多的项目使用CocoaPods,使用CocoaPods很有可能会用过JSONModel. JSONModel是个很强大的库,只要根据JSON定义好对应的类并继承JSONModel,就可以把JSO ...
- css补充、JavaScript、Dom
css补充: position: fixed:可以将标签固定在页面的某个位置 absolute+relative:通过两者的结合可以让标签在一个相对的位置 代码例子:(通过fixed标签将某些内容固定 ...