Home > OS >  Azure Automation - how to split out common functions
Azure Automation - how to split out common functions

Time:09-22

I'm wondering if there's a way I can define common functions in a separate runbook in Azure Automation? For instance, I've got a logging function that timestamps the messages and exits on errors that I use in multiple runbooks. I'd like to define it once, and then call it from the other runbooks. And if I change it in the future, I only have to change it in one place.

I know I can define parent / child runbooks and call them inline, which led me to wonder if I could split out, for instance, a function definition and then call that runbook from another runbook to "import" the function into the current runbook. So for instance, I have a runbook called "Test-FunctionDefinition" with the following code:

function Test-FunctionDefintion() {
  param (
    [String] $TestParam
  )
  Write-Output "Output from test function: $TestParam"
}

I'd like to be able to call it inline from another runbook like this to define the function, and then be able to use that function:

& .\Test-FunctionDefinition.ps1

Test-FunctionDefinition -TestParam "Test String"

I tried creating the two runbooks, but while it appears to call the runbook "Test-FunctionDefiniton" fine on line 1, subsequently calling the function on line 3 fails with:

Test-FunctionDefinition : The term 'Test-FunctionDefinition' is not recognized as the name of a cmdlet, function, script file, or operable program.

Is what I'm trying to do possible? I realize I could just modify my runbook and call & .\Test-FunctionDefinition.ps1 -TestParam "Test String", but would prefer to do it the other way if possible.

CodePudding user response:

It looks like it should be possible - Create modular runbooks in Automation

You have twop options:

  • Inline - Child runbooks run in the same job as the parent.
  • Cmdlet - A separate job is created for the child runbook.

For powershell runbook it should be easy as this

$vm = Get-AzVM -ResourceGroupName "LabRG" -Name "MyVM"
$output = .\PS-ChildRunbook.ps1 -VM $vm -RepeatCount 2 -Restart $true

CodePudding user response:

I did some more testing to make sure my original assumption (defining a function in one script and calling it in another) worked as I expected, and I got the same error. It appears that you need to dot-source rather than use the &. This worked both in a PowerShell console and Azure Automation:

. .\Test-FunctionDefinition.ps1

Test-FunctionDefinition -TestParam "Test String"

Note the starting '.' instead of '&'. I'll need to look up what the difference is between those...

  • Related