IT Consultant Everyday Notes

Just some problems/solutions storage

Tag Archives: Automation

Azure: Use Azure Key Vault to save passwords

Azure Automation: Send Email from Azure Automation Script via GMAIL

I am working with Azure Automation scripts. One of them stops all my Lab VMs after working hours to save some money. Script is based on one from Automation Gallery, but I wanted to add a notification feature.

There are several posts about using O365 for this, but I do not think it is a good idea since 0365 is not free.

I tried Outlook.com (AKA Hotmail) first, trying to stick with Microsoft platform, but did not get any success (authentication kept failed for me). So, the second choice was Gmail.com. From some posts I understood Azure does not have root certificates from GMAIL CA and SSL connection does not work. To workaround the issue I downloaded Google root certificate and created a Certificate Asset in Automation console

SNAGHTML9554a11d

Interesting enough I do not need to use it in my script apparently simply existence of it is enough….

Here is the script to check if all machines are in stop(Deallocated) state and send email otherwise. The script uses a PS Credential Asset: ‘Azure Credentials’ and my MSDN Platform subscription.

I created a test account at Gmail: azure.automation.service@gmail.com and add an Automation Asset (PS Credentials) including Gmail user name and password – “Gmailcreds” that allows do not put user name/password in the script.

workflow test-mail
{
$Cred = Get-AutomationPSCredential -Name ‘Azure Credentials’
$Gmailcreds = Get-AutomationPSCredential -Name ‘Gmailcerds’
Add-AzureAccount -Credential $Cred
Select-AzureSubscription -SubscriptionName “MSDN Platforms”
$vms = Get-AzureVM
$ss=””
ForEach ($vm in $vms ) {
if ($vm.Status -ne “StoppedDeallocated”) {$ss=$ss+$vm.name+” – “+$vm.Status + “`r`n”}
}
if ($ss -ne “”) {
$mail_body= ‘Attention! One or more VMs are in a state other than “Stopped (Deallocated)”‘ `
+”`r`n”+$ss
Send-MailMessage -SmtpServer smtp.gmail.com -Port 587 -Credential $Gmailcreds `
-UseSsl -From ‘azure.automation.service@gmail.com’ -To ‘alex.XXXXX@XXX.com’ `
-Subject ‘Alarm: Azure Automation – Running VM!’ -body $mail_body
}
}

This script can be added to schedule to run every night.