syntax to resize an Azure virtual machine programatically

Viewed 164

Using C#, how do I resize an Azure virtual machine that is already stopped? The Microsoft documentation is non-existent or impossible to discover. In my .Net Standard 2.0 class library I am referencing the Nuget package Microsoft.Azure.Management.Fluent 1.37.1 and have tried the code below.

using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
...

// get Azure client
string clientId = ...;
string clientSecret = ...;
string subscriptionId = ...;
string tenantId = ...;
AzureEnvironment env = ...;
AzureCredentials creds = new AzureCredentialsFactory().FromServicePrincipal(clientId, clientSecret, tenantId, env);
IAzure azure = Microsoft.Azure.Management.Fluent.Azure
                   .Configure()
                   .WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
                   .Authenticate(creds)
                   .WithSubscription(subscriptionId);

// get virtual machine
string resourceGroupName = "MyResourceGroup";
string machineName = "MyHostname";
IVirtualMachine vm = await azure.VirtualMachines.GetByResourceGroupAsync(resourceGroupName, machineName)

// resize virtual machine
VirtualMachineSizeTypes size = ...;
vm.Inner.HardwareProfile.VmSize = size;
vm.Inner.Validate();
vm.Update();  // nothing happens, virtual machine does not resize

On the last line, vm.Update() does nothing. In the Azure portal I can see that the virtual machine has not resized even after refreshing the portal multiple times.

2 Answers

The Azure API discoverability is terrible. I finally got resize working. Replace the last 3 lines

vm.Inner.HardwareProfile.VmSize = size;
vm.Inner.Validate();
vm.Update();

with

VirtualMachineUpdate parameters = new VirtualMachineUpdate()
{
    HardwareProfile = new HardwareProfile(size),
};
VirtualMachineInner response = await azure.VirtualMachines.Inner.UpdateAsync(resourceGroupName, vm.Name, parameters);

You had it almost right. Update() is a fluent operator:

var size = VirtualMachineSizeTypes.StandardB2s;
await vm.Update()
 .WithSize(size)
 .ApplyAsync();
Related