normalian blog

Let's talk about Microsoft Azure, ASP.NET and Java!

Execute Azure Automation Runbooks with Managed Identity

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.

  1. Create your Azure Automation account
  2. Enable Managed Identity on your Azure Automation account and assign proper RBAC roles
  3. Import "Az.Accounts" and "Az.Compute" modules to execute Az PowerShell commands on your Runbooks
  4. 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.
f:id:waritohutsu:20210425031827p:plain

Next, click "Azure role assignments" to assign "Virtual Machine Contributor" role to retrieve Azure VMs.
f:id:waritohutsu:20210425031957p:plain

Choose "Scope" as you need and choose "Virtual Machine Contributor" role like below.
f:id:waritohutsu:20210425035403p:plain

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.
f:id:waritohutsu:20210425035902p:plain

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.
f:id:waritohutsu:20210425040041p:plain

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.
f:id:waritohutsu:20210425040407p:plain