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...