- Article
- 9 minutes to read
This tutorial will guide you through creating aPowerShell-Workflow-Runbookin Azure Automation. PowerShell Workflow runbooks are text runbooks based on Windows PowerShell Workflow. You can create and edit runbook code using the text editor in the Azure portal.
observation
This article applies to PowerShell 5.1; PowerShell 7.1 (preview) and PowerShell 7.2 (preview) do not support workflows.
In this tutorial you will learn how to:
- Create a PowerShell workflow runbook
- Test and publish the runbook
- Running and tracking runbook job status
- Add authentication to manage Azure resources
- Update runbook parameters to start an Azure virtual machine
If you don't have an Azure subscription, create oneAccount for freeBefore you start.
requirements
- An Azure Automation account with at least one user-assigned managed identity. For more information, seeEnable Managed Identity.
- The Module:
Die Accounts
EThe.Compute
imported into the Automation account. For more information, seeimport the modules. - two or moreAzure virtual machines. Since you're stopping and starting these machines, they shouldn't be production VMs.
- OAzure The PowerShell Moduleinstalled on your computer. To install or update, seeHow to install the Azure Az PowerShell module.
Assign Permissions to Managed Identities
Assign the appropriate permissionsmanaged identityso you can stop a virtual machine. The runbook can use the automation account's system-assigned managed identity or a user-assigned managed identity. Steps are provided for assigning permissions to each identity. The following steps use the Azure portal. If you prefer PowerShell, seeAssign Azure Roles using Azure PowerShell.
get connectedAzure-Portaland navigate to your automation account.
SobAccount Settings, to chooseIdentity (view).
Doassigned to the systemguide, belowPermissions, to chooseAzure Role Assignmentsto open theAzure Role Assignmentsbook page.
To choose+ Add role assignment (preview)to open theAdd Role Assignment (Preview)book page.
Select the appropriate values.
(Video) Create and Run PowerShell Runbooks in Azure AutomationProperty Description Scope Scope is a group of resources to which the role assignment applies. Select from the drop-down listresource group. Enrollment This field should automatically populate with your signature. resource group From the drop-down list, select the resource group to which you want to grant identity permissions. role Select from the drop-down listDevTest Labs Users. To choosesave not computerand then close theAzure Role Assignmentspage to go backassigned to the systemAba.
To chooseassigned to userAba.
Select your user-assigned managed identity from the list to openmanaged identitybook page.
Note oClient IDfor later use.
Select from the menu on the leftAzure Role Assignmentsand then+ Add role assignment (preview)to open theAdd Role Assignment (Preview)book page.
Select the appropriate values.
Property Description Scope Select from the drop-down listresource group. Enrollment This field should automatically populate with your signature. resource group From the drop-down list, select the resource group to which you want to grant identity permissions. role Select from the drop-down listDevTest Labs Users. To choosesave not computerand then close theAzure Role Assignmentspage to go backassigned to userAba.
Create a new runbook
Start by creating a simplePowerShell-Workflow-Runbook. A benefit of Windows PowerShell workflows is the ability to run a series of commands in parallel rather than sequentially like a typical script.
observation
With the release, creating runbooks offers a new experience in the Azure portal. if you chooseracing booksblade >Create a race book, a new pageCreate a race bookopens with applicable options.
From your Automation account page opened atProcess automation, to chooseracing books
To choose+ Create a runbook.
(Video) Powershell Runbooks | Azure Automation Powershell Tutorial- Name the runbook. For example testing.
- Dorunbook typeSelect the dropdown menuPowerShell workflow.
- Doruntime versiondrop-down list, select5.1.
- Enter what is applicableDescription.
- To chooseTo create.
Add code to runbook
You can type code directly into the runbook, or you can select cmdlets, runbooks, and library control assets and add them to the runbook with all associated parameters. For this tutorial, you will enter the code directly into the runbook.
Your runbook is currently empty and contains only the necessaryworkflow
Keyword, the name of the runbook, and keys that include the entire workflow.
Workflow MyFirstRunbook-Workflow{}
You can use the...
Parallel
Keyword to create a script block with multiple commands running simultaneously. Enter the following codein betweenas chaves:Parallel { Write-Output "Parallel" Get-Date Start-Sleep -s 3 Get-Date } Write-Output " `r`n"Write-Output "Non-Parallel" Get-DateStart-Sleep -s 3Get-Date
Save the runbook by selectingsave not computer.
test the runbook
Before publishing the runbook to make it available in production, you should test it to ensure that it works correctly. When you test a runbook, your draft version runs and you can interactively view its output.
To choosestaging areato open theTestbook page.
To chooseTo startto start the exam. ARunbook-Jobcreated and its status displayed on the dashboard.
The job status starts with Queued, indicating that the job is waiting for a runbook worker to be made available in the cloud. The status changes to Starting when a worker claims the job. Finally, the Running status is when the runbook is actually running.
When the runbook job completes, theTestThe page displays your output. The output should be similar to the image below:
Check the output. All in
Parallel
block, including thestart sleeping
Command executed simultaneously. The same commands outsideParallel
The block was executed sequentially, as indicated by the different timestamps.to closeTestpage to return to the screen.
Publish and launch the runbook
The runbook you created is still in draft mode. You must publish it before running it in production. When you publish a runbook, you replace the existing published version with the draft version. In this case, you don't have a published version yet because you just created the runbook.
To choosePostto publish the runbook and thenEwhen solicited.
OStatusfield is now showingPublished. Review the options above to start the runbook now, schedule a future start time, or create oneWebhookso that the runbook can be started via an HTTP call. To chooseTo startand thenEwhen asked to start the runbook.
(Video) Azure Automation Tutorial | Automate PowerShell executionATo workThe created runbook job page opens. In that case, keep the page open to follow the progress of the work. OStatusThe field corresponds to the statuses you saw when testing the runbook.
After runbook status is shownaccomplished, to chooseExit. The output should look like the test output.
to closeTo workPage to return to runbookoverviewbook page.
Sobresources, to choosejobs. This page lists all jobs created by your runbook. You should only see one job listed because you only ran the job once.
Select the job to open itTo workPage you viewed when you started the runbook. Use this page to view details of all jobs created for the runbook. to closeTo workPage to return to runbookoverviewbook page.
Add authentication to manage Azure resources
You've tested and published your runbook, but so far it hasn't done anything useful. You want it to manage Azure resources. This is only possible when authenticating with signing credentials. The runbook uses the system-assigned managed identity of the automation account to authenticate with Azure to perform the management action on the VM. The runbook can easily be modified to use a user-assigned managed identity.
To chooseoverviewand thenTo editto open the text editor.
Replace the existing code with the following:
Workflow MyFirstRunbook-Workflow{$resourceGroup = "resourceGroupName"# Make sure you don't inherit an AzContext in your runbook -AzContext –SubscriptionID "<SubscriptionID>" }
edit the
$resourceGroup
Variable with a valid value that represents your resource group.If you want the runbook to run with the system-assigned managed identity, leave the code as is. If you prefer to use a user-assigned managed identity, do the following:
- Remove from line 9
Connect-AzAccount Identity
, - replace with
Connect-AzAccount -Identity -AccountId <ClientId>
, E - Enter the Customer ID you received earlier.
- Remove from line 9
To choosesave not computerand thenstaging area.
To chooseTo startto start the exam. When this is complete, you should see output similar to the following, showing basic account information. This action confirms that the credentials are valid.
to closeTestpage to return to the screen.
Add code to start a virtual machine
Now that your runbook is authenticated with your Azure subscription, you can manage resources. Add a command to start a virtual machine. You can choose any VM in your Azure subscription and hard-code that name into the runbook for now.
Add the following code as the last line before the closing bracket. Substitute
VM-Name
with the real name of a VM.(Video) Azure Automation Tutorial | PowerShell Runbook | bestdotnettrainingStart-AzVM -Name "VMName" -ResourceGroupName $resourceGroup -DefaultProfile $AzureContext
Test the runbook and verify that the VM has started. Then go back to the screen.
Add input parameters to the runbook
Your runbook is starting the VM you coded in the runbook. It's more useful if you can specify the VM when the runbook starts. Add input parameters to the runbook to provide this functionality.
replace line 3,
$resourceGroup = "resourceGroupName"
, with the following:Param( [string]$resourceGroup, [string]$VMName)
replace the previous
Start-AzVM
command with the following:Start-AzVM -Name $VMName -ResourceGroupName $resourceGroup -DefaultProfile $AzureContext
Test the runbook and verify that the VM has started. Then go back to the screen.
Manage multiple VMs at the same time
You can use the...ForEach-Parallel
Build to process commands for each element in a collection at the same time. Review the code for the runbook now:
- Accept a collection of virtual machine names,
- Accept a parameter to stop or start the virtual machines and
- Run actions in parallel for all virtual machines
Replace all existing code with the following:
Workflow MyFirstRunbook-Workflow{Param( [string]$resourceGroup, [string[]]$VMs, [string]$action)# Ensures you don't inherit an AzContext in your runbookDisable-AzContextAutosave -Scope Process# Connect to Azure with the system -assigned managed identityConnect-AzAccount -Identity# Set context and save$AzureContext = Set-AzContext –SubscriptionId "<SubscriptionID>" # Start or stop VMs in parallelif($action -eq "Start") { ForEach -Parallel($ vm in $VMs) { Start-AzVM -Name $vm -ResourceGroupName $resourceGroup -DefaultProfile $AzureContext } }elseif ($action -eq "Stop") { ForEach -Parallel ($vm in $VMs) { Stop-AzVM -Name $vm - ResourceGroupName $resourceGroup -DefaultProfile $AzureContext -Force } }else { Write-Output "`r`n Action not allowed. Enter 'Stop' or 'Start'."}}
If you want the runbook to run with the system-assigned managed identity, leave the code as is. If you prefer to use a user-assigned managed identity, do the following:
- Remove from line 9
Connect-AzAccount Identity
, - replace with
Connect-AzAccount -Identity -AccountId <ClientId>
, E - Enter the Customer ID you received earlier.
- Remove from line 9
To choosesave not computer, ThenPost, and thenEwhen solicited.
Dooverviewpage, selectTo start.
Fill in the parameters and selectOK.
Parameter Description RESOURCE GROUP Enter the VMs resource group name. VMs Enter the virtual machine names using the following syntax: ["VM1","VM2","VM3"]
Action Prohibited fuses
orTo start
.Navigate to your list of virtual machines and refresh the page every few seconds. Note that the action is done in parallel for each VM. Without this
-Parallel
keyword, the actions would be executed sequentially. Since VMs are started one by one, each VM can reach theOperationPhase at slightly different times based on the characteristics of each VM.
clean resources
If you no longer want to use this runbook, delete it using the following steps:
- Navigate to your automation account.
- SobProcess automation, to chooseracing books.
- Select the runbook.
- from the newspaperoverviewpage, selectextinguish.
Next steps
In this tutorial, you created a PowerShell workflow runbook. To take a look at Python 3 runbooks, see:
Tutorial: Creating a Python 3 Runbook (Preview)