What is a method for checking where an Azure Automation runbook (PowerShell) is running?

Viewed 946

I'm writing a set of PowerShell runbooks in Azure Automation. Some of them run on-premises (ala Hybrid Runbook Worker) and some in Azure directly.

I'd like to immediately error and exit any hybrid scripts if they are accidentally kicked off in Azure (since it's the default selection when using the portal).

I thought I check by getting the results of Get-AutomationConnection -Name AzureRunAsConnection but it takes about 4 seconds to respond, but it also returns values when run via Hybrid Worker. Does anyone know of a better/quicker method?

Thanks!

Update: A one-liner that is crude but seems to work is:

Try {$AmIInAzure = Get-AzureRmEnvironment AzureCloud -ErrorAction Stop;Throw "This runbook must be run on-premises via Hybrid Runbook Worker.  Exiting."} Catch {}

The variable $AmIInAzure is simply used to hide the output of Get-AzureRMEnvironment, while the Try..Catch is to hide any errors. If this code is run in Azure, it will throw the specified text and the runbook will error out (as desired). If it is run on a hybrid worker, it doesn't do anything (allowing the rest of the runbook to run).

I'm curious if anyone might have a better method.

Update 2: That oneliner doesn't seem to work, as neither throw, exit, or break will cause the runbook to exit. Still looking for a working method...

2 Answers

You could test using $PSPrivateMetadata

  begin {
        if ($null -eq $PSPrivateMetadata) {
            throw "This command can only be run within the context of an Azure Automation Runbook Worker"
        }
    }

I had the exact same problem and did not get it to work. Ended up with another solution, I´m just running this at the top of my runbook, or directly after my param list if you have input parameters.

$checkHybridWorker = hostname

if ($checkHybridWorker -ne "myhybridworkerhostname"){

        Write-Warning "Job must be started from Hybrid worker, exiting."
        Exit 1

}

Not pretty but it works fine.

Related