Search code examples
azure-automationazure-runbook

Azure Runbook check status


There is an Azure Automation runbook, which runs Powershell script below. It checks if runbook has running jobs already, and if no, execute some script.

The problem:

If I run it on "Test Pane" it works fine, but once I run via schedule or start as a job, it always exists with an output job is running. There are no jobs running and running code from my laptop it shows not running as well. Why it goes well on a Runbook test pane, but fails on normal run?

param (
[string]$runbook = "test-rb",
[string]$rgName = "test-rg",
[string]$aaName = "test-aa"
)

$jobs = Get-AzAutomationJob -ResourceGroupName $rgName -AutomationAccountName $aaName -RunbookName $runbook
#$Jobs.status

# Check to see if it is already running

if (($jobs.status -contains "Running") -Or ($jobs.Status -eq "New"))
{   
    Write-Output "Runbook execution is stopped [$runbook] - there is another job currently running."
    exit 1
} 
else
{
    Write-Output "Proceed with runbook execution [$runbook]  - there are no interfering jobs running."
}

try {
    ....my script
}
catch {
    ....something something
}

Solution

  • Becasue when you run the job, it will get itself as a Running job via the command Get-AzAutomationJob, add the Write-Output $jobs in your script, see the screenshot below, notice the Id and the JobId is the same.

    enter image description here

    To solve the issue, you could use $jobs = $jobs[1..($jobs.Length-1)], it will exclude itself, then the script will work fine.

    My sample:

    $connectionName = "AzureRunAsConnection"
    try
    {
        # Get the connection "AzureRunAsConnection "
        $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName         
    
        "Logging in to Azure..."
        $null = Add-AzAccount `
            -ServicePrincipal `
            -TenantId $servicePrincipalConnection.TenantId `
            -ApplicationId $servicePrincipalConnection.ApplicationId `
            -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 
    }
    catch {
        if (!$servicePrincipalConnection)
        {
            $ErrorMessage = "Connection $connectionName not found."
            throw $ErrorMessage
        } else{
            Write-Error -Message $_.Exception
            throw $_.Exception
        }
    }
    $jobs = Get-AzAutomationJob -ResourceGroupName <resourcegroup-name> -AutomationAccountName joyauto1 -RunbookName test1
    $jobs = $jobs[1..($jobs.Length-1)]
    if (($jobs.status -contains "Running") -Or ($jobs.Status -eq "New"))
    {   
        Write-Output "Runbook execution is stopped [] - there is another job currently running."
        exit 1
    } 
    else
    {
        Write-Output "Proceed with runbook execution []  - there are no interfering jobs running."
    }
    

    enter image description here