Azure Automation: Your first Runbook with PowerShell

October 27, 2015 at 2:55 pm in Azure, Azure Automation, PowerShell by Florent

Today, I will show you How to run your first Azure Automation Runbook.

To start this article, I have one Azure subscription, with an Active Directory linked:

SNAGHTMLc2d20

The first step will be to create a new user in this directory to execute the PowerShell runbook on Azure Automation. This account will be a standard user, but he will have the administrator rights on the subscription where the runbook will be executed:

image

image

SNAGHTMLf7287

image

Now, logout and login with this user and the temporary password to change it. When it’s done, go to https://portal.azure.com and select Automation Accounts:

image

Click on Add and complete each questions:

image

When the Automation account is created, go inside the account and select Assets. On this part, we will provide the credential to launch the runbook, a variable that we will use later in the script and a schedule for the script.

Click on Credentials > Add a credential:

image

Do the same in Variables section:

image

And with Schedules:

image

When it’s done, go back to the welcome of the Automation Accounts and select Runbooks:

image

Create a new Runbook, with the name Connect-AzureSubscription and PowerShell as Runbook type. This runbook will take your Azure credentials, provided in the Credentials section:

image

Complete with the following script, by replacing by your own values:

$Cred = Get-AutomationPSCredential -Name ‘SCUGBECred’
Add-AzureAccount -Credential $Cred

Select-AzureSubscription -SubscriptionName “Free Trial”

Click on Save and on Published:

image

Create a new Runbook, named Get-AzureVM. Paste the following script:

.\Connect-AzureSubscription.ps1
$VMNames = Get-AutomationVariable -Name ‘VMName’
$VMName = $VMNames.split(“,”);

foreach($VM in $VMName){

$serviceName = Get-AzureVM | Where {($_.Name -eq $VM)}
$service = $serviceName.ServiceName
$status = $serviceName.PowerState
Write-Output “The VM $VM with service name $service is $status”

}

You can test it with the Test pane:

SNAGHTML6edc9d

As you can see, the check is done on the 2 vm names that I wrote in my variable VMName. Click on Publish. Click on Schedule to execute the script every hour:

image

You can go on the Jobs part to see if the job has been executed correctly and see the Output. It’s possible to modify the script to send an email and so on:

image

image

This automation is very cool in case of development  environment. You can schedule to stop all VM at 9pm and restart all VM at 6AM for example.

Don’t hesitate to contact me if you want more information or help Sourire