Skip to content

Commit 1869e5b

Browse files
authored
Merge pull request #113200 from BethWilke/branch205
Fixing documentation task 1711520
2 parents a159569 + 402a1ce commit 1869e5b

File tree

4 files changed

+387
-388
lines changed

4 files changed

+387
-388
lines changed

articles/automation/automation-runbook-execution.md

Lines changed: 140 additions & 131 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ ms.subservice: process-automation
66
ms.date: 04/14/2020
77
ms.topic: conceptual
88
---
9+
910
# Runbook execution in Azure Automation
1011

1112
Process automation in Azure Automation allows you to create and manage PowerShell, PowerShell Workflow, and graphical runbooks. For details, see [Azure Automation runbooks](automation-runbook-types.md).
@@ -32,7 +33,7 @@ The following diagram shows the lifecycle of a runbook job for [PowerShell runbo
3233
Runbooks in Azure Automation can run on either an Azure sandbox or a [Hybrid Runbook Worker](automation-hybrid-runbook-worker.md). When runbooks are designed to authenticate and run against resources in Azure, they run in an Azure sandbox, which is a shared environment that multiple jobs can use. Jobs using the same sandbox are bound by the resource limitations of the sandbox.
3334

3435
>[!NOTE]
35-
>The Azure sandbox environment does not support interactive operations. It also requires the use of local MOF files for runbooks that make Win32 calls.
36+
>The Azure sandbox environment does not support interactive operations. It prevents access to all out-of-process COM servers. It also requires the use of local MOF files for runbooks that make Win32 calls.
3637
3738
You can use a Hybrid Runbook Worker to run runbooks directly on the computer that hosts the role and against local resources in the environment. Azure Automation stores and manages runbooks and then delivers them to one or more assigned computers.
3839

@@ -79,137 +80,9 @@ else
7980
}
8081
```
8182

82-
## Supporting time-dependent scripts
83-
84-
Your runbooks must be robust and capable of handling transient errors that can cause them to restart or fail. If a runbook fails, Azure Automation retries it.
85-
86-
If your runbook normally runs within a time constraint, have the script implement logic to check the execution time. This check ensures the running of operations such as startup, shutdown, or scale-out only during specific times.
87-
88-
> [!NOTE]
89-
> The local time on the Azure sandbox process is set to UTC. Calculations for date and time in your runbooks must take this fact into consideration.
90-
91-
## Tracking progress
92-
93-
It's a good practice to author your runbooks to be modular in nature, with logic that can be reused and restarted easily. Tracking progress in a runbook is a good way to ensure that the runbook logic executes correctly if there are issues. It's possible to track the progress of a runbook by using an external source, such as a storage account, a database, or shared files. You can create logic in your runbook to first check the state of the last action taken. Then, based on the result of the check, the logic can either skip or continue specific tasks in the runbook.
94-
95-
## Preventing concurrent jobs
96-
97-
Some runbooks behave strangely if they run across multiple jobs at the same time. In this case, it's important for a runbook to implement logic to determine if there is already a running job. Here's a basic example.
98-
99-
```powershell
100-
# Authenticate to Azure
101-
$connection = Get-AutomationConnection -Name AzureRunAsConnection
102-
Connect-AzAccount -ServicePrincipal -Tenant $connection.TenantID `
103-
-ApplicationId $connection.ApplicationID -CertificateThumbprint $connection.CertificateThumbprint
83+
## Using self-signed certificates
10484

105-
$AzContext = Select-AzSubscription -SubscriptionId $connection.SubscriptionID
106-
107-
# Check for already running or new runbooks
108-
$runbookName = "<RunbookName>"
109-
$rgName = "<ResourceGroupName>"
110-
$aaName = "<AutomationAccountName>"
111-
$jobs = Get-AzAutomationJob -ResourceGroupName $rgName -AutomationAccountName $aaName -RunbookName $runbookName -AzContext $AzureContext
112-
113-
# Check to see if it is already running
114-
$runningCount = ($jobs | ? {$_.Status -eq "Running"}).count
115-
116-
If (($jobs.status -contains "Running" -And $runningCount -gt 1 ) -Or ($jobs.Status -eq "New")) {
117-
# Exit code
118-
Write-Output "Runbook is already running"
119-
Exit 1
120-
} else {
121-
# Insert Your code here
122-
}
123-
```
124-
125-
## Working with multiple subscriptions
126-
127-
To deal with multiple subscriptions, your runbook must use the [Disable-AzContextAutosave](https://docs.microsoft.com/powershell/module/Az.Accounts/Disable-AzContextAutosave?view=azps-3.5.0) cmdlet. This cmdlet ensures that the authentication context isn't retrieved from another runbook running in the same sandbox. The runbook also uses the`AzContext` parameter on the Az module cmdlets and passes it the proper context.
128-
129-
```powershell
130-
# Ensures that you do not inherit an AzContext in your runbook
131-
Disable-AzContextAutosave –Scope Process
132-
133-
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
134-
Connect-AzAccount -ServicePrincipal `
135-
-Tenant $Conn.TenantID `
136-
-ApplicationId $Conn.ApplicationID `
137-
-CertificateThumbprint $Conn.CertificateThumbprint
138-
139-
$context = Get-AzContext
140-
141-
$ChildRunbookName = 'ChildRunbookDemo'
142-
$AutomationAccountName = 'myAutomationAccount'
143-
$ResourceGroupName = 'myResourceGroup'
144-
145-
Start-AzAutomationRunbook `
146-
-ResourceGroupName $ResourceGroupName `
147-
-AutomationAccountName $AutomationAccountName `
148-
-Name $ChildRunbookName `
149-
-DefaultProfile $context
150-
```
151-
152-
## Handling exceptions
153-
154-
This section describes some ways to handle exceptions or intermittent issues in your runbooks. An example is a WebSocket exception. Correct exception handling prevents transient network failures from causing your runbooks to fail.
155-
156-
### ErrorActionPreference
157-
158-
The [ErrorActionPreference](/powershell/module/microsoft.powershell.core/about/about_preference_variables#erroractionpreference) variable determines how PowerShell responds to a non-terminating error. Terminating errors always terminate and are not affected by `ErrorActionPreference`.
159-
160-
When the runbook uses `ErrorActionPreference`, a normally non-terminating error such as `PathNotFound` from the [Get-ChildItem](https://docs.microsoft.com/powershell/module/microsoft.powershell.management/get-childitem?view=powershell-7) cmdlet stops the runbook from completing. The following example shows the use of `ErrorActionPreference`. The final [Write-Output](https://docs.microsoft.com/powershell/module/microsoft.powershell.utility/write-output?view=powershell-7) command never executes, as the script stops.
161-
162-
```powershell-interactive
163-
$ErrorActionPreference = 'Stop'
164-
Get-ChildItem -path nofile.txt
165-
Write-Output "This message will not show"
166-
```
167-
168-
### Try Catch Finally
169-
170-
[Try Catch Finally](/powershell/module/microsoft.powershell.core/about/about_try_catch_finally) is used in PowerShell scripts to handle terminating errors. The script can use this mechanism to catch specific exceptions or general exceptions. The `catch` statement should be used to track or try to handle errors. The following example tries to download a file that does not exist. It catches the `System.Net.WebException` exception and returns the last value for any other exception.
171-
172-
```powershell-interactive
173-
try
174-
{
175-
$wc = new-object System.Net.WebClient
176-
$wc.DownloadFile("http://www.contoso.com/MyDoc.doc")
177-
}
178-
catch [System.Net.WebException]
179-
{
180-
"Unable to download MyDoc.doc from http://www.contoso.com."
181-
}
182-
catch
183-
{
184-
"An error occurred that could not be resolved."
185-
}
186-
```
187-
188-
### Throw
189-
190-
[Throw](/powershell/module/microsoft.powershell.core/about/about_throw) can be used to generate a terminating error. This mechanism can be useful when defining your own logic in a runbook. If the script meets a criterion that should stop it, it can use the `throw` statement to stop. The following example uses this statement to show a required function parameter.
191-
192-
```powershell-interactive
193-
function Get-ContosoFiles
194-
{
195-
param ($path = $(throw "The Path parameter is required."))
196-
Get-ChildItem -Path $path\*.txt -recurse
197-
}
198-
```
199-
200-
## Using executables or calling processes
201-
202-
Runbooks that run in Azure sandboxes don't support calling processes, such as executables (**.exe** files) or subprocesses. The reason for this is that an Azure sandbox is a shared process run in a container that might not be able to access all the underlying APIs. For scenarios requiring third-party software or calls to subprocesses, you should execute a runbook on a [Hybrid Runbook Worker](automation-hybrid-runbook-worker.md).
203-
204-
## Accessing device and application characteristics
205-
206-
Runbook jobs that run in Azure sandboxes can't access any device or application characteristics. The most common API used to query performance metrics on Windows is WMI, with some of the common metrics being memory and CPU usage. However, it doesn't matter what API is used, as jobs running in the cloud can't access the Microsoft implementation of Web-Based Enterprise Management (WBEM). This platform is built on the Common Information Model (CIM), providing the industry standards for defining device and application characteristics.
207-
208-
## Handling errors
209-
210-
Your runbooks must be capable of handling errors. PowerShell has two types of errors, terminating and non-terminating. Terminating errors stop runbook execution when they occur. The runbook stops with a job status of Failed.
211-
212-
Non-terminating errors allow a script to continue even after they occur. An example of a non-terminating error is one that occurs when a runbook uses the `Get-ChildItem` cmdlet with a path that doesn't exist. PowerShell sees that the path doesn't exist, throws an error, and continues to the next folder. The error in this case doesn't set runbook job status to Failed, and the job might even be completed. To force a runbook to stop on a non-terminating error, you can use `ErrorAction Stop` on the cmdlet.
85+
To use self-signed certificates in your runbooks, see [Creating a new certificate](https://docs.microsoft.com/azure/automation/shared-resources/certificates#creating-a-new-certificate).
21386

21487
## Handling jobs
21588

@@ -337,6 +210,142 @@ foreach ($log in $JobActivityLogs)
337210
$JobInfo.GetEnumerator() | sort key -Descending | Select-Object -First 1
338211
```
339212

213+
## Tracking progress
214+
215+
It's a good practice to author your runbooks to be modular in nature, with logic that can be reused and restarted easily. Tracking progress in a runbook is a good way to ensure that the runbook logic executes correctly if there are issues. It's possible to track the progress of a runbook by using an external source, such as a storage account, a database, or shared files. You can create logic in your runbook to first check the state of the last action taken. Then, based on the result of the check, the logic can either skip or continue specific tasks in the runbook.
216+
217+
## Preventing concurrent jobs
218+
219+
Some runbooks behave strangely if they run across multiple jobs at the same time. In this case, it's important for a runbook to implement logic to determine if there is already a running job. Here's a basic example.
220+
221+
```powershell
222+
# Authenticate to Azure
223+
$connection = Get-AutomationConnection -Name AzureRunAsConnection
224+
Connect-AzAccount -ServicePrincipal -Tenant $connection.TenantID `
225+
-ApplicationId $connection.ApplicationID -CertificateThumbprint $connection.CertificateThumbprint
226+
227+
$AzContext = Select-AzSubscription -SubscriptionId $connection.SubscriptionID
228+
229+
# Check for already running or new runbooks
230+
$runbookName = "<RunbookName>"
231+
$rgName = "<ResourceGroupName>"
232+
$aaName = "<AutomationAccountName>"
233+
$jobs = Get-AzAutomationJob -ResourceGroupName $rgName -AutomationAccountName $aaName -RunbookName $runbookName -AzContext $AzureContext
234+
235+
# Check to see if it is already running
236+
$runningCount = ($jobs | ? {$_.Status -eq "Running"}).count
237+
238+
If (($jobs.status -contains "Running" -And $runningCount -gt 1 ) -Or ($jobs.Status -eq "New")) {
239+
# Exit code
240+
Write-Output "Runbook is already running"
241+
Exit 1
242+
} else {
243+
# Insert Your code here
244+
}
245+
```
246+
247+
## Handling exceptions
248+
249+
This section describes some ways to handle exceptions or intermittent issues in your runbooks. An example is a WebSocket exception. Correct exception handling prevents transient network failures from causing your runbooks to fail.
250+
251+
### ErrorActionPreference
252+
253+
The [ErrorActionPreference](/powershell/module/microsoft.powershell.core/about/about_preference_variables#erroractionpreference) variable determines how PowerShell responds to a non-terminating error. Terminating errors always terminate and are not affected by `ErrorActionPreference`.
254+
255+
When the runbook uses `ErrorActionPreference`, a normally non-terminating error such as `PathNotFound` from the [Get-ChildItem](https://docs.microsoft.com/powershell/module/microsoft.powershell.management/get-childitem?view=powershell-7) cmdlet stops the runbook from completing. The following example shows the use of `ErrorActionPreference`. The final [Write-Output](https://docs.microsoft.com/powershell/module/microsoft.powershell.utility/write-output?view=powershell-7) command never executes, as the script stops.
256+
257+
```powershell-interactive
258+
$ErrorActionPreference = 'Stop'
259+
Get-ChildItem -path nofile.txt
260+
Write-Output "This message will not show"
261+
```
262+
263+
### Try Catch Finally
264+
265+
[Try Catch Finally](/powershell/module/microsoft.powershell.core/about/about_try_catch_finally) is used in PowerShell scripts to handle terminating errors. The script can use this mechanism to catch specific exceptions or general exceptions. The `catch` statement should be used to track or try to handle errors. The following example tries to download a file that does not exist. It catches the `System.Net.WebException` exception and returns the last value for any other exception.
266+
267+
```powershell-interactive
268+
try
269+
{
270+
$wc = new-object System.Net.WebClient
271+
$wc.DownloadFile("http://www.contoso.com/MyDoc.doc")
272+
}
273+
catch [System.Net.WebException]
274+
{
275+
"Unable to download MyDoc.doc from http://www.contoso.com."
276+
}
277+
catch
278+
{
279+
"An error occurred that could not be resolved."
280+
}
281+
```
282+
283+
### Throw
284+
285+
[Throw](/powershell/module/microsoft.powershell.core/about/about_throw) can be used to generate a terminating error. This mechanism can be useful when defining your own logic in a runbook. If the script meets a criterion that should stop it, it can use the `throw` statement to stop. The following example uses this statement to show a required function parameter.
286+
287+
```powershell-interactive
288+
function Get-ContosoFiles
289+
{
290+
param ($path = $(throw "The Path parameter is required."))
291+
Get-ChildItem -Path $path\*.txt -recurse
292+
}
293+
```
294+
295+
## Handling errors
296+
297+
Your runbooks must be capable of handling errors. PowerShell has two types of errors, terminating and non-terminating. Terminating errors stop runbook execution when they occur. The runbook stops with a job status of Failed.
298+
299+
Non-terminating errors allow a script to continue even after they occur. An example of a non-terminating error is one that occurs when a runbook uses the `Get-ChildItem` cmdlet with a path that doesn't exist. PowerShell sees that the path doesn't exist, throws an error, and continues to the next folder. The error in this case doesn't set runbook job status to Failed, and the job might even be completed. To force a runbook to stop on a non-terminating error, you can use `ErrorAction Stop` on the cmdlet.
300+
301+
## Using executables or calling processes
302+
303+
Runbooks that run in Azure sandboxes don't support calling processes, such as executables (**.exe** files) or subprocesses. The reason for this is that an Azure sandbox is a shared process run in a container that might not be able to access all the underlying APIs. For scenarios requiring third-party software or calls to subprocesses, you should execute a runbook on a [Hybrid Runbook Worker](automation-hybrid-runbook-worker.md).
304+
305+
## Accessing device and application characteristics
306+
307+
Runbook jobs that run in Azure sandboxes can't access any device or application characteristics. The most common API used to query performance metrics on Windows is WMI, with some of the common metrics being memory and CPU usage. However, it doesn't matter what API is used, as jobs running in the cloud can't access the Microsoft implementation of Web-Based Enterprise Management (WBEM). This platform is built on the Common Information Model (CIM), providing the industry standards for defining device and application characteristics.
308+
309+
## Working with webhooks
310+
311+
External services, for example, Azure DevOps Services and GitHub, can start a runbook in Azure Automation. To do this type of startup, the service uses a [webhook](automation-webhooks.md) via a single HTTP request. Use of a webhook allows runbooks to be started without implementation of a full Azure Automation solution.
312+
313+
## Supporting time-dependent scripts
314+
315+
Your runbooks must be robust and capable of handling transient errors that can cause them to restart or fail. If a runbook fails, Azure Automation retries it.
316+
317+
If your runbook normally runs within a time constraint, have the script implement logic to check the execution time. This check ensures the running of operations such as startup, shutdown, or scale-out only during specific times.
318+
319+
> [!NOTE]
320+
> The local time on the Azure sandbox process is set to UTC. Calculations for date and time in your runbooks must take this fact into consideration.
321+
322+
## Working with multiple subscriptions
323+
324+
To deal with multiple subscriptions, your runbook must use the [Disable-AzContextAutosave](https://docs.microsoft.com/powershell/module/Az.Accounts/Disable-AzContextAutosave?view=azps-3.5.0) cmdlet. This cmdlet ensures that the authentication context isn't retrieved from another runbook running in the same sandbox. The runbook also uses the`AzContext` parameter on the Az module cmdlets and passes it the proper context.
325+
326+
```powershell
327+
# Ensures that you do not inherit an AzContext in your runbook
328+
Disable-AzContextAutosave –Scope Process
329+
330+
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
331+
Connect-AzAccount -ServicePrincipal `
332+
-Tenant $Conn.TenantID `
333+
-ApplicationId $Conn.ApplicationID `
334+
-CertificateThumbprint $Conn.CertificateThumbprint
335+
336+
$context = Get-AzContext
337+
338+
$ChildRunbookName = 'ChildRunbookDemo'
339+
$AutomationAccountName = 'myAutomationAccount'
340+
$ResourceGroupName = 'myResourceGroup'
341+
342+
Start-AzAutomationRunbook `
343+
-ResourceGroupName $ResourceGroupName `
344+
-AutomationAccountName $AutomationAccountName `
345+
-Name $ChildRunbookName `
346+
-DefaultProfile $context
347+
```
348+
340349
## <a name="fair-share"></a>Sharing resources among runbooks
341350

342351
To share resources among all runbooks in the cloud, Azure Automation temporarily unloads or stops any job that has run for more than three hours. Jobs for [PowerShell runbooks](automation-runbook-types.md#powershell-runbooks) and [Python runbooks](automation-runbook-types.md#python-runbooks) are stopped and not restarted, and the job status becomes Stopped.

0 commit comments

Comments
 (0)