3

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

BHall
  • 308
  • 1
  • 11

2 Answers2

0

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"
        }
    }
Boblol
  • 1
  • Thanks. this looks good. I can't try it as I am done with the project, but when I was developing mine, neither throw nor exit would kick me out of the script. Is this working for you? I wonder if it changed in the last 9 months – BHall Jun 21 '19 at 10:40
0

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.

Matthijs
  • 2,483
  • 5
  • 22
  • 33
Kris
  • 1
  • did you mean that the psprivatemetadata method did not work? I'm curious since I have not had an opportunity to test that method (and while developing my script last year, throw and exit did not work for me). – BHall Jun 21 '19 at 10:42