Tutorial: Create a PowerShell workflow runbook in Azure Automation (2023)

  • 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 AccountsEThe.Computeimported 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.

  1. get connectedAzure-Portaland navigate to your automation account.

  2. SobAccount Settings, to chooseIdentity (view).

  3. Doassigned to the systemguide, belowPermissions, to chooseAzure Role Assignmentsto open theAzure Role Assignmentsbook page.

    Tutorial: Create a PowerShell workflow runbook in Azure Automation (1)

  4. To choose+ Add role assignment (preview)to open theAdd Role Assignment (Preview)book page.

    Tutorial: Create a PowerShell workflow runbook in Azure Automation (2)

  5. Select the appropriate values.

    (Video) Create and Run PowerShell Runbooks in Azure Automation

    PropertyDescription
    ScopeScope is a group of resources to which the role assignment applies. Select from the drop-down listresource group.
    EnrollmentThis field should automatically populate with your signature.
    resource groupFrom the drop-down list, select the resource group to which you want to grant identity permissions.
    roleSelect from the drop-down listDevTest Labs Users.
  6. To choosesave not computerand then close theAzure Role Assignmentspage to go backassigned to the systemAba.

  7. To chooseassigned to userAba.

  8. Select your user-assigned managed identity from the list to openmanaged identitybook page.

    Tutorial: Create a PowerShell workflow runbook in Azure Automation (3)

  9. Note oClient IDfor later use.

    Tutorial: Create a PowerShell workflow runbook in Azure Automation (4)

  10. Select from the menu on the leftAzure Role Assignmentsand then+ Add role assignment (preview)to open theAdd Role Assignment (Preview)book page.

    Tutorial: Create a PowerShell workflow runbook in Azure Automation (5)

  11. Select the appropriate values.

    PropertyDescription
    ScopeSelect from the drop-down listresource group.
    EnrollmentThis field should automatically populate with your signature.
    resource groupFrom the drop-down list, select the resource group to which you want to grant identity permissions.
    roleSelect from the drop-down listDevTest Labs Users.
  12. 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.

  1. From your Automation account page opened atProcess automation, to chooseracing books

    Tutorial: Create a PowerShell workflow runbook in Azure Automation (6)

  2. To choose+ Create a runbook.

    (Video) Powershell Runbooks | Azure Automation Powershell Tutorial

    1. Name the runbook. For example testing.
    2. Dorunbook typeSelect the dropdown menuPowerShell workflow.
    3. Doruntime versiondrop-down list, select5.1.
    4. Enter what is applicableDescription.
    5. To chooseTo create.

    Tutorial: Create a PowerShell workflow runbook in Azure Automation (7)

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 necessaryworkflowKeyword, the name of the runbook, and keys that include the entire workflow.

Workflow MyFirstRunbook-Workflow{}
  1. You can use the...ParallelKeyword 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
  2. 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.

  1. To choosestaging areato open theTestbook page.

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

  3. When the runbook job completes, theTestThe page displays your output. The output should be similar to the image below:

    Tutorial: Create a PowerShell workflow runbook in Azure Automation (8)

    Check the output. All inParallelblock, including thestart sleepingCommand executed simultaneously. The same commands outsideParallelThe block was executed sequentially, as indicated by the different timestamps.

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

  1. To choosePostto publish the runbook and thenEwhen solicited.

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

    Tutorial: Create a PowerShell workflow runbook in Azure Automation (9)

    (Video) Azure Automation Tutorial | Automate PowerShell execution

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

    Tutorial: Create a PowerShell workflow runbook in Azure Automation (10)

  4. After runbook status is shownaccomplished, to chooseExit. The output should look like the test output.

  5. to closeTo workPage to return to runbookoverviewbook page.

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

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

  1. To chooseoverviewand thenTo editto open the text editor.

  2. 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$resourceGroupVariable with a valid value that represents your resource group.

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

    1. Remove from line 9Connect-AzAccount Identity,
    2. replace withConnect-AzAccount -Identity -AccountId <ClientId>, E
    3. Enter the Customer ID you received earlier.
  4. To choosesave not computerand thenstaging area.

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

    Tutorial: Create a PowerShell workflow runbook in Azure Automation (11)

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

  1. Add the following code as the last line before the closing bracket. SubstituteVM-Namewith the real name of a VM.

    (Video) Azure Automation Tutorial | PowerShell Runbook | bestdotnettraining

    Start-AzVM -Name "VMName" -ResourceGroupName $resourceGroup -DefaultProfile $AzureContext
  2. 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.

  1. replace line 3,$resourceGroup = "resourceGroupName", with the following:

    Param( [string]$resourceGroup, [string]$VMName)
  2. replace the previousStart-AzVMcommand with the following:

    Start-AzVM -Name $VMName -ResourceGroupName $resourceGroup -DefaultProfile $AzureContext
  3. 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-ParallelBuild 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
  1. 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'."}}
  2. 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:

    1. Remove from line 9Connect-AzAccount Identity,
    2. replace withConnect-AzAccount -Identity -AccountId <ClientId>, E
    3. Enter the Customer ID you received earlier.
  3. To choosesave not computer, ThenPost, and thenEwhen solicited.

  4. Dooverviewpage, selectTo start.

  5. Fill in the parameters and selectOK.

    ParameterDescription
    RESOURCE GROUPEnter the VMs resource group name.
    VMsEnter the virtual machine names using the following syntax:["VM1","VM2","VM3"]
    ActionProhibitedfusesorTo start.
  6. 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-Parallelkeyword, 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:

  1. Navigate to your automation account.
  2. SobProcess automation, to chooseracing books.
  3. Select the runbook.
  4. 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)

Videos

1. Understand Azure Automation Accounts and create runbooks | Azure PowerShell
(VRK solutions)
2. Azure Automation | Introduction to Azure Automation Account & PowerShell Runbook
(BestDotNetTraining)
3. Azure Automation and Runbook Introduction with PowerShell | Lecture 74
(CloudLearn)
4. Start Azure Automation Runbooks with Webhooks
(Travis Roberts)
5. Azure Automation Part1 - Working with PowerShell Runbooks to Automate Virtual Machine Creation
(Azure Training Series)
6. Introduction to Azure Automation
(Travis Roberts)

References

Top Articles
Latest Posts
Article information

Author: Clemencia Bogisich Ret

Last Updated: 30/05/2023

Views: 6035

Rating: 5 / 5 (60 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Clemencia Bogisich Ret

Birthday: 2001-07-17

Address: Suite 794 53887 Geri Spring, West Cristentown, KY 54855

Phone: +5934435460663

Job: Central Hospitality Director

Hobby: Yoga, Electronics, Rafting, Lockpicking, Inline skating, Puzzles, scrapbook

Introduction: My name is Clemencia Bogisich Ret, I am a super, outstanding, graceful, friendly, vast, comfortable, agreeable person who loves writing and wants to share my knowledge and understanding with you.