Search code examples
azure-automationazure-runbook

How to use Azure Runbooks to restart an Azure Web App on a schedule


We have an Azure Web App that we want to setup an automatic restart on a schedule. If I wanted to use Runbooks for this, how would I add one or multiple apps to automatically restart on different schedules?


Solution

  • There are a number of different ways to do this, and some will depend on the Azure-Runbook module versions you have.

    1. You need to setup a user as 'RunAsConnection' user
    2. To get a connection, you can use the cmdlet: Get-AutomationConnection
    3. Then to add an authenticated account, you use: Add-AzureRmAccount
    4. If you have multiple subscriptions, you will need to select the subscription to use: Select-AzureRmSubscription
    5. Finally, use Restart-AzureRmWebApp to restart the web app.

    If you set a $result= Restart-AzureRmWebApp, if the $result is null, then it didn't work, otherwise you will see the status of the running webapp. Eg. $result.State = "Running" if it worked successfully.

    To do this on a schedule: go to your Runbook > Schedules > Add Schedule.

    Add the input parameters, and select/create a recurring schedule. Click Ok and you're done!

    *** If you use a parameter for your webAppName, then you can reuse the runbook, and just add different schedules with different input params

    Sample Code.

    try
    {
        $servicePrincipalConnection= Get-AutomationConnection -Name "AzureRunAsConnection"
    
        # Logging in to Azure
        $account = Add-AzureRmAccount `
            -ServicePrincipal `
            -TenantId $servicePrincipalConnection.TenantId `
            -ApplicationId $servicePrincipalConnection.ApplicationId `
            -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
    
        Select-AzureRmSubscription -SubscriptionName "Azure subscription name"
    
        $result = Restart-AzureRmWebApp `
                    -ResourceGroupName "Resource Name"
                    -Name "Name of webapp you want to restart"
    
        if($result)
        {
            $state = $result.State
            Write-Output ("Web app restarted and is now $state")  #State should be Running at this point
        }
       else
       {
            Write-Output ("Web app did NOT restart")
       }
    }
    catch
    {
        Write-Output ("Web app did NOT restart")
        throw $_.Exception
    }