之前发的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. 页面引入flash

    function shFlashObj(id, data, oWidth, oHeight, flashvals,beFullScreen) {    var swf='<object id=& ...

  2. C#拾遗-接口与抽象类

    抽象类中可以有构造函数(无参构造函数和有参构造函数)无参构造函数在子类实例化时被调用有参构造函数必须显示调用 抽象类中可以有抽象方法 但是不能有方法体,子类必须实现抽象方法子类必须重写抽象类中的抽象方 ...

  3. 被swoole坑哭的PHP程序员

    被swoole坑哭的PHP程序员 2015-09-16 09:57 文帅营 博客园 字号:T | T 首先说一下对swoole的理解:披着PHP外衣的C程序.很多PHPer朋友看到swoole提供的强 ...

  4. Unity运行时检测Altas使用情况

    UI贴图在游戏中内存大小中占的分量非常非常大,尤其对于前期对UI没有规划的项目,无论是包量还是内存大小都是需要花费很多时间去优化.如果涉及到战斗场景和逻辑场景的情况下,常用的做法就是把两个场景使用的a ...

  5. JS学习总结(新手)

    1. JS面向对象 http://www.cnblogs.com/JavascriptDream/p/5064976.html a. Prototype 属性的理解 b. 遗传继承函数 functio ...

  6. 前端开发自学之JavaScript——显示当前时间

    <html> <head> <title>JavaScript</title> <script language="javascript ...

  7. Update Request

    public function update(UpdateAppointmentRequest $request) { try { $data = array_filter($request-> ...

  8. Android--ListView与数据绑定(Xamarin)

    ListView 控件是一个条目容器, 用于显示集合对象(如数组, List<T>, ObservableCollection<T>等)的每一个条目, 并提供滚动功能. 列表视 ...

  9. freebsd启动报错:My unqualified host name unkown...Sleeping for retry.

    原文 http://blog.163.com/sujoe_2006/blog/static/335315120111158576591/ 病状:启动报"My unqualified host ...

  10. remi

    很简单呀,又不用自己编译.用 http://rpms.remirepo.net/ 这个 remi 的包,直接 yum install php-swoole 就完事了 安装remi包也很简单, yum  ...