skip to Main Content

This is my code to create vm in Azure using the Azure SDK fluent. My question is: I need to set auto shutdown option while creating VM, I need to set the time while creating the VM so in that case the VM will get poweroff when the time arrives. Is that possible? Please let me know.

public async Task<VmResponse> DoCreateVm(VMConfigurationParameter objvm)
{
        VmResponse response = new VmResponse();
        LogDAL objlog = new LogDAL();
        var usernameWithoutSpaces = objvm.UserName.Replace(" ", "");
        var vNetName = $"{char.ToUpper(usernameWithoutSpaces.Replace(".", "")[0])}{usernameWithoutSpaces.Replace(".", "").Substring(1, Math.Min(5, usernameWithoutSpaces.Replace(".", "").Length - 1))}{objvm.UserNumber.ToString().Substring(Math.Max(0, objvm.UserNumber.ToString().Length - 6))}-vnet";
        var vNetAddress = "172.16.0.0/16";
        var subnetName = "default";
        var subnetAddress = "172.16.0.0/24";
        var nicName = $"{char.ToUpper(objvm.UserName.Replace(" ", "").Replace(".", "")[0])}{objvm.UserName.Replace(" ", "").Replace(".", "").Substring(1, Math.Min(5, objvm.UserName.Replace(" ", "").Length - 1))}{objvm.UserNumber.ToString().Substring(Math.Max(0, objvm.UserNumber.ToString().Length - 6))}";
        var publicIPName = $"{char.ToUpper(objvm.UserName.Replace(" ", "").Replace(".", "")[0])}{objvm.UserName.Replace(" ", "").Replace(".", "").Substring(1, Math.Min(5, objvm.UserName.Replace(" ", "").Length - 1))}{objvm.UserNumber.ToString().Substring(Math.Max(0, objvm.UserNumber.ToString().Length - 6))}";
        var nsgName = $"{char.ToUpper(objvm.UserName.Replace(" ", "").Replace(".", "")[0])}{objvm.UserName.Replace(" ", "").Replace(".", "").Substring(1, Math.Min(5, objvm.UserName.Replace(" ", "").Length - 1))}{objvm.UserNumber.ToString().Substring(Math.Max(0, objvm.UserNumber.ToString().Length - 6))}";
        var username = $"{char.ToUpper(objvm.UserName.Replace(" ", "").Replace(".", "")[0])}{objvm.UserName.Replace(" ", "").Replace(".", "").Substring(1, Math.Min(5, objvm.UserName.Replace(" ", "").Length - 1))}{objvm.UserNumber.ToString().Substring(Math.Max(0, objvm.UserNumber.ToString().Length - 6))}";
        var userpassword = $"{char.ToUpper(objvm.UserName.Replace(" ", "").Replace(".", "")[0])}{objvm.UserName.Replace(" ", "").Replace(".", "").Substring(1, Math.Min(5, objvm.UserName.Replace(" ", "").Length - 1))}@{objvm.UserNumber.ToString().Substring(Math.Max(0, objvm.UserNumber.ToString().Length - 6))}";
        var vmname = $"{char.ToUpper(objvm.UserName.Replace(" ", "").Replace(".", "")[0])}{objvm.UserName.Replace(" ", "").Replace(".", "").Substring(1, Math.Min(5, objvm.UserName.Replace(" ", "").Replace(".", "").Length - 1))}{objvm.UserNumber.ToString().Substring(Math.Max(0, objvm.UserNumber.ToString().Length - 6))}-VM";

        try
        {
                string filePath = ConfigurationManager.AppSettings["Credentials"];
                var credentials = SdkContext.AzureCredentialsFactory.FromFile(filePath);
                filePath = string.Empty;
                var azure = Azure.Authenticate(credentials).WithDefaultSubscription();
                string vm_ResGroup = "SSIS_Student"; 
                var resourceGroupName = await DoGetResourceGroupName(azure, vm_ResGroup);
                var details_resgrp = await DoGetResourceGroupName(azure, objvm.ExamName); //getting main details from the main resource group
                var (galleryname, imagename) = await DoGetGalleryImageDetails(azure, objvm.ExamName);
                if (resourceGroupName != "" && galleryname != "" && imagename != "" && details_resgrp!="")
                {
                    var captureImage = azure.GalleryImages.GetByGallery(details_resgrp, galleryname, imagename);
                if (captureImage != null)
                {
                    //var security = captureImage.RecommendedVirtualMachineConfiguration;

                    //var regionName = await getRegion();
                    var network = azure.Networks.Define(vNetName)
                            .WithRegion(captureImage.Location)
                            .WithExistingResourceGroup(resourceGroupName)
                            .WithAddressSpace(vNetAddress)
                            .WithSubnet(subnetName, subnetAddress)
                            .Create();
                    var nsg = azure.NetworkSecurityGroups.Define(nsgName)
                        .WithRegion(captureImage.Location)
                        .WithExistingResourceGroup(resourceGroupName)
                        .DefineRule("Allow-RDP")
                            .AllowInbound()
                            .FromAnyAddress()
                            .FromAnyPort()
                            .ToAnyAddress()
                            .ToPort(3389)
                            .WithProtocol(SecurityRuleProtocol.Tcp)
                            .WithPriority(100)
                            .Attach()
                        .Create();
                    var publicIP = azure.PublicIPAddresses.Define(publicIPName)
                            .WithRegion(captureImage.Location)
                            .WithExistingResourceGroup(resourceGroupName)
                            .WithStaticIP()
                            .Create();
                    //You need a network security group for controlling the access to the VM

                    var nic = azure.NetworkInterfaces.Define(nicName)
                             .WithRegion(captureImage.Location)
                             .WithExistingResourceGroup(resourceGroupName)
                             .WithExistingPrimaryNetwork(network)
                             .WithSubnet(subnetName)
                             .WithPrimaryPrivateIPAddressDynamic()
                             .WithExistingPrimaryPublicIPAddress(publicIP)
                             .WithExistingNetworkSecurityGroup(nsg)
                             .Create();

                    //var security = security

                    var newVM = azure.VirtualMachines.Define(vmname)
                        
                                                     .WithRegion(captureImage.Location)
                                                     
                                                     .WithExistingResourceGroup(resourceGroupName)
                                                     
                                                     .WithExistingPrimaryNetworkInterface(nic)
                                                     
                                                     .WithWindowsCustomImage(captureImage.Id)
                                                     
                                                     .WithAdminUsername(username)
                                                     
                                                     .WithAdminPassword(userpassword)
                                                     
                                                     .WithComputerName(vmname)
                                                     
                                                     .WithSize(VirtualMachineSizeTypes.StandardD4sV3)
                                                     
                                                     .Create();
                    // newVM.Restart();

                    response.responseCode = "200";
                    response.responseMessage = "VM Created";
                    response.ipAddress = publicIP.Inner.IpAddress.ToString();
                    response.userName = username;
                    response.userPassword = userpassword;
                    response.vmname = vmname;
                    response.region = newVM.RegionName;
                    response.vmId = newVM.Id;

                    if (newVM != null)
                    {
                        DateTime shutdown = DateTime.Now.AddHours(4);
                        ScheduleShutdown(newVM.Id, shutdown, azure);
                    }
                }
                else
                {
                        response.responseCode = "100";
                        response.responseMessage = "VM Not able to create";
                }
            }
            else
            {
                    response.responseCode = "400";
                    response.responseMessage = "Resource-Group , Image Not exist";
            }
        }           
        catch (Exception ex)
        {
            var message = ex.Message.ToString();
            //objlog.LogExceptionToFile(message);
            response.responseCode = "500";
            response.responseMessage = message;
        }

        return response;
    }

I need a solution to auto shutdown while creating VM using Azure SDK fluent and C#

2

Answers


  1. Try adding these to azure.VirtualMachines.Define(vmname):

    .withAutoShutdown()
    .withShutdownMode(AutoShutdownSchedulePowerState.STOP_VM)
    .withTimeZone("Eastern Standard Time")
    // Change to your desired timezone
    .withDailyUsageTime("2100")
    // 24 hour format shutdown time (HHmm)
    

    .

    Login or Signup to reply.
  2. To automate the shutdown of an Azure Virtual Machine using the Azure SDK for .NET (specifically the Fluent API), you can leverage Azure Automation to schedule a shutdown job. Here’s a step-by-step guide on how to achieve this:

    • Create an Azure Automation Account: If you haven’t already, create an
      Azure Automation account in your Azure subscription.

    • Import Required Modules: Inside your Azure Automation account, import
      the required modules. Specifically, you’ll need the Az.Accounts,
      Az.Compute, and Az.Resources modules.

    • Create a Runbook: Create a PowerShell runbook in your Azure
      Automation account. This runbook will contain the script to shut down
      your VM. Here’s an example of a PowerShell script to shut down a VM:

      param(
      [string]$ResourceGroupName,
      [string]$VMName
      )

      $connection = Get-AutomationConnection -Name AzureRunAsConnection
      Connect-AzAccount -ServicePrincipal -Tenant $connection.TenantID -ApplicationId $connection.ApplicationID -CertificateThumbprint $connection.CertificateThumbprint

      $vm = Get-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName

      Stop-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName -Force

    • Schedule the Runbook: In your Azure Automation account, schedule the
      runbook to execute at the desired time. You can specify the desired
      shutdown time as a parameter when scheduling the runbook.

    • Invoke the Runbook from Your C# Code: Modify your C# code to invoke
      the Azure Automation runbook after creating the VM. You’ll need to
      use the Microsoft.Azure.Management.Automation package to interact
      with Azure Automation from your C# code. Here’s an example of how
      you can invoke the runbook:

      using Microsoft.Azure.Management.Automation;
      using Microsoft.Azure.Management.Automation.Models;

      public async Task ScheduleShutdown(string resourceGroupName, string vmName, DateTime shutdownTime)
      {
      var serviceClient = new AutomationManagementClient(credentials); // Initialize AutomationManagementClient with your credentials

       // Prepare the parameters for the runbook
       var parameters = new Dictionary<string, object>
       {
           { "ResourceGroupName", resourceGroupName },
           { "VMName", vmName }
       };
      
       // Schedule the runbook
       var jobId = await serviceClient.Job.ScheduleWithHttpMessagesAsync(
           "yourAutomationAccountName",
           "yourRunbookName",
           parameters,
           startTime: shutdownTime,
           runOn: null, // You can specify the target hybrid worker group here if needed
           isDraft: false
       );
      
       Console.WriteLine($"Shutdown job scheduled. Job ID: {jobId}");
      

      }

    Replace "yourAutomationAccountName" and "yourRunbookName" with the name of your Azure Automation account and the name of your PowerShell runbook, respectively.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search