How to Clone and manage a virtual machine in Azure

2020-03-30 07:28发布

I have followed the guidelines on how to manage virtual machines using C# and could create a sample program based on it.

However, In addition I have a use case where we want to clone multiple virtual machines and manage them remotely using a console program written in C#. I could find the ways to clone a VM via power shell, but I could not find anywhere how can I create a clone and eventually manage the cloned VM on Azure.

Can anyone please give me a direction on how I can use .Net SDK to achieve this use case?

Thanks

1条回答
Deceive 欺骗
2楼-- · 2020-03-30 08:22

We can do that with Microsoft.Azure.Management.Fluent and WindowsAzure.Storage.

I create a demo for it and it works correctly for me. The following is my detail steps.

As you mentioned link. Firstly we need to deallocate the VM. Before that we need to get authentication to operation resource in the Azure.

1.Get Azure object using an authentication file, how to create an authentication file please refer to document. Before that we need to registry an Azure AD Application and assign corresponding role for it, more details please refer to the document. Then we can get the clientId, key(secret key) and tenant from the Azure AD App. The file format as following

subscription=########-####-####-####-############
client=########-####-####-####-############
key=XXXXXXXXXXXXXXXX
tenant=########-####-####-####-############
managementURI=https\://management.core.windows.net/
baseURL=https\://management.azure.com/
authURL=https\://login.windows.net/
graphURL=https\://graph.windows.net/

Create the Microsoft.Azure.Management.Fluent.Azure object

 var credentials = SdkContext.AzureCredentialsFactory.FromFile(@"path of authentication file");

 var azure = Azure

                .Configure()

                .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)

                .Authenticate(credentials)

                .WithDefaultSubscription()

2.Deallocate the VM with C# code.

azure.VirtualMachines.PowerOff(resourcegroup,vmName);  //shutdown the VM
azure.VirtualMachines.Deallocate(resourcegroup, vmName); //deallocate the VM

3.Get the VM Disk Vhd uri Info with code

 var vm = azure.VirtualMachines.GetByGroup(resourcegroup, vmName);
 string vhdUri= vm.StorageProfile.OsDisk.Vhd.Uri;  //result :  https://storageaccountname.blob.core.windows.net/vhds/blob.vhd

4.From the vhduri then we can get Storage Account and blobname.

5.Start to copy blob to the target container, more details about operating blob please refer to the document.

        var account = azure.StorageAccounts.GetByGroup(resourcegroup,storageaccount);

        var key = account.GetKeys()[0];

        CloudStorageAccount storageAccount = CloudStorageAccount.Parse("connectionstring");
        // Create a CloudFileClient object for credentialed access to File storage.
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference("tomvhds");
        CloudBlobContainer sourceBlobContainer = blobClient.GetContainerReference("vhds");
        container.CreateIfNotExists();
        CloudPageBlob destBlob = container.GetPageBlobReference(destinationBlob);
        CloudPageBlob sourcePageBlob = sourceBlobContainer.GetPageBlobReference(sourceblob);
        destBlob.StartCopy(sourcePageBlob);
        copyVhdurl =  destBlob.Uri.ToString();

6.Create the Disk for creating vm

 var disk = azure.Disks.Define("diskname") 
               .WithRegion(location)
               .WithExistingResourceGroup(resourcegroup)
               .WithWindowsFromVhd(copyvhduri)
               .Create();

7.Create the VM and check from the Azure portal

 var windowsVm = azure.VirtualMachines.Define(machinename)

                   .WithRegion(location)  //eastasia

                   .WithNewResourceGroup(resourcegroupName)

                   .WithNewPrimaryNetwork("10.0.0.0/28")

                   .WithPrimaryPrivateIpAddressDynamic()

                   .WithNewPrimaryPublicIpAddress("dnslab")

                   .WithSpecializedOsDisk(disk, OperatingSystemTypes.Windows)

                   .WithSize(VirtualMachineSizeTypes.StandardA0)

                   .Create();

enter image description here

enter image description here

packages.config file

 <?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.Azure.KeyVault.Core" version="1.0.0" targetFramework="net452" />
  <package id="Microsoft.Azure.Management.AppService.Fluent" version="1.0.0-beta50" targetFramework="net452" />
  <package id="Microsoft.Azure.Management.Batch.Fluent" version="1.0.0-beta50" targetFramework="net452" />
  <package id="Microsoft.Azure.Management.Cdn.Fluent" version="1.0.0-beta50" targetFramework="net452" />
  <package id="Microsoft.Azure.Management.Compute.Fluent" version="1.0.0-beta50" targetFramework="net452" />
  <package id="Microsoft.Azure.Management.Dns.Fluent" version="1.0.0-beta50" targetFramework="net452" />
  <package id="Microsoft.Azure.Management.Fluent" version="1.0.0-beta50" targetFramework="net452" />
  <package id="Microsoft.Azure.Management.Graph.RBAC.Fluent" version="1.0.0-beta50" targetFramework="net452" />
  <package id="Microsoft.Azure.Management.KeyVault.Fluent" version="1.0.0-beta50" targetFramework="net452" />
  <package id="Microsoft.Azure.Management.Network.Fluent" version="1.0.0-beta50" targetFramework="net452" />
  <package id="Microsoft.Azure.Management.Redis.Fluent" version="1.0.0-beta50" targetFramework="net452" />
  <package id="Microsoft.Azure.Management.ResourceManager.Fluent" version="1.0.0-beta50" targetFramework="net452" />
  <package id="Microsoft.Azure.Management.Sql.Fluent" version="1.0.0-beta50" targetFramework="net452" />
  <package id="Microsoft.Azure.Management.Storage.Fluent" version="1.0.0-beta50" targetFramework="net452" />
  <package id="Microsoft.Azure.Management.TrafficManager.Fluent" version="1.0.0-beta50" targetFramework="net452" />
  <package id="Microsoft.Data.Edm" version="5.8.2" targetFramework="net452" />
  <package id="Microsoft.Data.OData" version="5.8.2" targetFramework="net452" />
  <package id="Microsoft.Data.Services.Client" version="5.8.2" targetFramework="net452" />
  <package id="Microsoft.IdentityModel.Clients.ActiveDirectory" version="2.28.3" targetFramework="net452" />
  <package id="Microsoft.Rest.ClientRuntime" version="2.3.5" targetFramework="net452" />
  <package id="Microsoft.Rest.ClientRuntime.Azure" version="3.3.5" targetFramework="net452" />
  <package id="Microsoft.Rest.ClientRuntime.Azure.Authentication" version="2.2.10" targetFramework="net452" />
  <package id="Newtonsoft.Json" version="6.0.8" targetFramework="net452" />
  <package id="System.ComponentModel.EventBasedAsync" version="4.0.11" targetFramework="net452" />
  <package id="System.Dynamic.Runtime" version="4.0.0" targetFramework="net452" />
  <package id="System.Linq.Queryable" version="4.0.0" targetFramework="net452" />
  <package id="System.Net.Requests" version="4.0.11" targetFramework="net452" />
  <package id="System.Spatial" version="5.8.2" targetFramework="net452" />
  <package id="WindowsAzure.Storage" version="8.1.1" targetFramework="net452" />
</packages>
查看更多
登录 后发表回答