How to Fix Azure Start and Stop VM using Runbook in Automation Account?

Guzzu, Navya X 25 Reputation points
2024-02-07T18:25:56.84+00:00

Hi All, I have a requirement to auto startup and shutdown the Azure VM in Business hours(i.e 9 AM- 5 PM ) Mon-Fri. Have created a Automation Accounts, Configured Runbook and created a schedule. I'm unable to link a runbook to schedule as it got depreciated in sep2023. On Attempt-1, Throwing error as this.client.subscriptionId is null. However, have tried to hardcoded the subscription Id, still same error. In Below snippet, "Get Subscription" also throws the same error. ###################Attempt-1:##########################

$resourceGroupName = "XXX" $vmName = "YYY" 
try 
{
 "Logging in to Azure..." 
Connect-AzAccount -Identity 
} 
catch 
{ 
Write-Error -Message $.Exception throw $.Exception 
}
#Get subscription details
$subscriptions = Get-AzSubscription
#Output subscription details
$subscriptions | Select-Object SubscriptionName, SubscriptionId 
Write-Output ("Subscription"+$subscriptions) 
Stop-AzVM -ResourceGroupName "XXX" -Name $vmName -Force

Result: It gives error as Subscription is null.

---On Attempt-2, We have tried to authenticate the certificate by providing the tenant id, app_id unable to provide the thumbprint as I have no permissions to fetch. Still it throws the same error "Subscription is null." Used the authentication by Managed identity approach. #######################Attempt-2:#####################################

$resourceGroupName = "XXX" 
$vmName = "YYY" 

$Cert = Get-AzAutomationCertificate -ResourceGroupName "XXX" -AutomationAccountName "VM-AutoStartandStop" -Name "AzureRunAsCertificate" 

Write-Output ("Cert"+$Cert) 
try 
{
 "Logging in to Azure..." 
Connect-AzAccount -Identity 
}
 catch 
{
 Write-Error -Message $.Exception throw $.Exception 
}
Connect-AzAccount -ServicePrincipal -Tenant "
Azure Automation
Azure Automation
An Azure service that is used to automate, configure, and install updates across hybrid environments.
1,196 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jackson Martins 10,141 Reputation points MVP
    2024-02-09T18:11:49.53+00:00

    There is a simpler script with the command just to startup the vm, you can use the script below:

    Param(
     [string]$VmName,
     [string]$ResourceGroupName,
     [ValidateSet("Startup", "Shutdown")]
     [string]$VmAction
    )
    $Conn = Get-AutomationConnection -Name AzureRunAsConnection
    Add-AzureRMAccount -ServicePrincipal -Tenant $Conn.TenantID `
    -ApplicationID $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint
    Start-AzureRmVM -Name VMNAME -ResourceGroupName RGNAME
    

    Put it in the schedule to turn on the VM And to shut down the vm you use the auto shutdown feature on Virtual Machine User's image

    Get in touch if you need more help with this issue. --please don't forget to "[Accept the answer]" if the reply is helpful--

    2 people found this answer helpful.

5 additional answers

Sort by: Most helpful
  1. Guzzu, Navya X 25 Reputation points
    2024-02-09T17:08:40.2433333+00:00

    Hi @Jackson Martins , When I try to create a runbook now, it throws error as -"Too many tags "and gives request Invalid. User's image

    1 person found this answer helpful.

  2. Jackson Martins 10,141 Reputation points MVP
    2024-02-08T23:19:38.6+00:00

    Hi @Guzzu, Navya X To enable TAG parameters, first of all, you need to create identity permissions:

    User's image

    Then you need to create a schedule and, after that, you need to open the schedule and modify TAG Parameters User's image

    You can test using parameters User's image


  3. Jackson Martins 10,141 Reputation points MVP
    2024-02-07T18:39:15.5533333+00:00

    HI @Guzzu, Navya X You can try this:

    Click Identity. User's image

    Click Azure role assignments to give the managed identity permissions to access subscription resources. User's image

    Click add and give permissions to the resource group where your vms are. User's image

    With the identity account created, within the automation resource, click on runbook. User's image

    Fill in the runbook information as shown in the following image: User's image

    Click in the field on the right and paste the command from above:

    Param(
      [Parameter(Mandatory = $true)]
      [String]
      $TagName,
      [Parameter(Mandatory = $true)]
         
      [String]
      $TagValue,
      [Parameter(Mandatory = $true)]
      [Boolean]
      $Shutdown
    )
    # Autentication in Azure
    ## Ensures you do not inherit an AzContext in your runbook
    Disable-AzContextAutosave -Scope Process
    ## Connect to Azure with System-assigned managed identity
    $AzureContext = (Connect-AzAccount -Identity).context
    #Write-Output -InputObject $AzureContext
    ## Set and store context
    $AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext
    #Write-Output -InputObject $AzureContext
    ## Start and Stop VMs
      $vms = Get-AzResource -TagName $TagName -TagValue $TagValue | Where-Object -FilterScript {
        $_.ResourceType -like 'Microsoft.Compute/virtualMachines' 
      }
      Foreach ($vm in $vms) 
      {
        if ($Shutdown -eq $true) 
        {
          Write-Output -InputObject "Stopping $($vm.Name)"        
          Stop-AzVM -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Force
        }
        else 
        {
          Write-Output -InputObject "Starting $($vm.Name)"        
          Start-AzVM -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName
        }
      }
    
    
    

    It will look like this:User's image

    Publish Fill in according to the needs of your environment. Pay attention to the time zone. Click create. User's image

    he configuration will return to the previous screen. Now click on the settings parameters. Fill in according to the tags you configured on the VM, in shutdown put true if you want to turn off the VM and false if you want to turn it on. User's image

    Get in touch if you need more help with this issue. --please don't forget to "[Accept the answer]" if the reply is helpful--

    0 comments No comments

  4. Guzzu, Navya X 25 Reputation points
    2024-02-08T15:02:55.05+00:00

    Hi @Jackson Martins , Thanks for getting back on the above query and providing well defined steps to follow. For Identity-> Role assignment, Do I need to get the write permissions on subscription please correct me If I'm wrong. Is any other additional permissions to be assigned ? Below screenshot doesn't show any parameters in schedule. User's image User's image

    In Above screenshot tried to create the parameters, unable to proceed further. Please suggest the next steps.

    0 comments No comments