In past, it was required to execute Runbooks on Azure Automation by using RunAsAccount, but it's still mandatory to renew a self-signed certificate - as far as I remember, it would be annual. This renewal sometimes causes issues because some folks are unfamiliar about this.
Now, Azure Automation has just started to support for Managed Identity. This enable you not to force the renewal, and you can simplify your Runbooks scripts not only the renewal. In this article, you can run through to setup a Runbook Retrieving running VMs on your subscription.
Steps retrieving running VMs on your subscription
Follow steps are below.
- Create your Azure Automation account
- Enable Managed Identity on your Azure Automation account and assign proper RBAC roles
- Import "Az.Accounts" and "Az.Compute" modules to execute Az PowerShell commands on your Runbooks
- Create a Runbook and put PowerShell scripts
Enable Managed Identity on your Azure Automation account
I believe we can skip "Create your Azure Automation account" because it's too trivial. It's quite simple to enable Managed Identity on Azure Automation. Visit your Azure Automation account and choose new item named "Identity" like below. Then, switch "Status" as "On" and save it.
Next, click "Azure role assignments" to assign "Virtual Machine Contributor" role to retrieve Azure VMs.
Choose "Scope" as you need and choose "Virtual Machine Contributor" role like below.
Import "Az.Accounts" and "Az.Compute" modules to execute Az PowerShell commands on your Runbooks
Azure Automation accounts don't import Azure Az PowerShell modules as default at this April 2021. Choose "Modules" from left side menus, and click "Browse gallery" button like below.
Put "Az" in search box, so you can find all Az modules like below. Az modules has dependencies for each others, so import "Az.Accounts" first, and then import "Az.Compute" as next.
Create a Runbook and put PowerShell scripts
Create new Runbook on your Azure Automation account and put scripts below.
Connect-AzAccount -Identity Get-AzVM -Status | Where-Object PowerState -Like "*Running*" | Format-Table -AutoSize
Execute your Runbook and then you can find output below on "Job" menu.