This is similar to my other blog post I did recently on sequentially starting and stopping virtual machines where I demonstrated setting up Azure automation using a normal user account in Azure AD as the credential.
There is also another blog post I did about setting up SPNs (Service Principal Names) in Azure AD – similar to service accounts.
So this blog post merges both Azure Automation and SPNs for credentials together.
The difference being, you just need to add an additional Azure Automation Variable for the Azure Tenant ID. You’ll will need to set yourself up an SPN first using my script, then go ahead and setup an Azure Automation account as per this post.
The Tenant ID Variable can be added as per the screenshots below.
Then added to the script as per….
The two scripts are listed below….
Start-Up Script:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
workflow Startup_VM | |
{ | |
$Cred = Get-AutomationPSCredential –Name "Credential_Name" | |
$tenant = Get-AutomationVariable –Name "tenant" | |
Login–AzureRmAccount –Credential $Cred –ServicePrincipal –TenantId $tenant | |
$subscription = Get-AutomationVariable –Name "subscription" | |
Select-AzureRmSubscription –SubscriptionName $subscription | |
$VMs = Get-AzureRmVM | where {$_.Name -match 'Virtual_Machine_Name'} | |
ForEach –Parallel ($VM in $VMs) | |
{ | |
Stop-AzureRmVM –Name $VM.Name –ResourceGroupName $VM.ResourceGroupName –Force | |
} | |
} |
Shutdown Script:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
workflow Shutdown_VM | |
{ | |
$Cred = Get-AutomationPSCredential –Name "Credential_Name" | |
$tenant = Get-AutomationVariable –Name "tenant" | |
Login–AzureRmAccount –Credential $Cred –ServicePrincipal –TenantId $tenant | |
$subscription = Get-AutomationVariable –Name "subscription" | |
Select-AzureRmSubscription –SubscriptionName $subscription | |
$VMs = Get-AzureRmVM | where {$_.Name -match 'Virtual_Machine_Name'} | |
ForEach –Parallel ($VM in $VMs) | |
{ | |
Stop-AzureRmVM –Name $VM.Name –ResourceGroupName $VM.ResourceGroupName –Force | |
} | |
} |