Search code examples
azureazure-web-app-serviceazure-automation

Azure PowerShell - Restart-AzWebApp : Object reference not set to an instance of an object


I try to use the following content to restart my webapp-service in Azure. And I deploy this script in Azure Automation Runbook.

Connect-AzAccount -Identity
Set-AzContext -Tenant "<secret-uuid>"
Write-Output "Start"
Restart-AzWebApp -ResourceGroupName "testconfogproxy_group" -Name "testconfogproxy"
Write-Output "Finished"

But I got an error message Object reference not set to an instance of an object. after it executed the Restart-AzWebApp.

I don't know why and I also don't know how can I solve it.


Solution

  • Object reference not set to an instance of an object this issue related to the authentication method you are using to connect to your Azure account.

    enter image description here

    You can make use of below modified script to restart the webapp service in Azure in Azure Automation Runbook

    $Appid = "your-application-id"
    $PWord = ConvertTo-SecureString -String "your-clinet-secret" -AsPlainText -Force
    $tenant = "<your-tenant-id>"
    $Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $Appid,$PWord
    Connect-AzAccount -Credential $Credential -Tenant $tenant -ServicePrincipal -Subscription "<Your-subscription-id>"
    Write-Output "Start"
    Restart-AzWebApp -ResourceGroupName "Venkat" -Name "webappv1"
    Write-Output "Finished"
    
    

    Make sure to add contributor role for App at the subscription level

    Output:

    Environments                                                                                                            
    ------------                                                                                                            
    {[AzureChinaCloud, AzureChinaCloud], [AzureCloud, AzureCloud], [AzureGermanCloud, AzureGermanCloud], [AzureUSGovernme...
    Start
    
    GitRemoteName               : 
    GitRemoteUri                : 
    GitRemoteUsername           : 
    GitRemotePassword           : 
    AzureStorageAccounts        : 
    AzureStoragePath            : {}
    State                       : Stopped
    HostNames                   : {webappv1.azurewebsites.net}
    RepositorySiteName          : webappv1
    ................
    ............
    
    

    enter image description here