Automatic Windows Azure Instance reboot notification
Once in a while it would be very nice to get an automatic notification if one of your instances in a Windows Azure role get's rebootet.
(This will happen for example if the underlying operation system is updated automatically; which btw. is a really great benefit of PaaS!)
Let me describe a very simple approach that avoids touching the code of your Web/Worker Role at all!
1, Simply create a external (console) process that can send email to you.
(you can use and email provider you like, sendgrid actually offers 25000 emails/month for free https://sendgrid.com/azure.html)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace reboot_notify
{
class reboot_notify
{
static void Main(string[] args)
{
string instanceid="";
System.Net.Mail.MailMessage message;
System.Net.Mail.SmtpClient smtp;
instanceid = System.Environment.GetEnvironmentVariable("ENV_ROLEID");
System.Net.NetworkCredential nc = new NetworkCredential(<USERNAME>,<PASSWORD>);
message = new System.Net.Mail.MailMessage();
message.To.Add(<Email_receiver>);
message.From = new System.Net.Mail.MailAddress(<FROM_ADRESS>);
message.Body = "";
message.Subject = "Notification email: Instance " +instanceid +" rebooted";
smtp = new System.Net.Mail.SmtpClient(>YOUR_EMAIL_SERVICE>);
smtp.Credentials = nc;
smtp.Send(message);
}
}
}
2, The trick now is to use the <Startup> tag in your Azure *.csdef file together with the (not very well known) <Environment> feature
<?xml version="1.0" encoding="utf-8"?>
<ServiceDefinition name="myhost" xmlns="https://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition">
<WebRole name="WebRole1" vmsize="Small">
<Startup>
<Task commandLine="reboot_notify.exe" taskType="background" executionContext="elevated">
<Environment>
<Variable name="ENV_ROLEID">
<RoleInstanceValue xpath="/RoleEnvironment/CurrentInstance/@id" />
</Variable>
</Environment>
</Task>
</Startup>
[...]
Your email process will be spawned up and will automatically see the current Instance_ID in a variable called (in this sample) ENV_ROLEID.
Of course it can be very easily retrieved by using something like:
instanceid = System.Environment.GetEnvironmentVariable("ENV_ROLEID");
as shown in the sample code above.
3, Simply include your reboot_notify.exe as shown below into your azure deployment package. (DO NOT FORGET to set the "Copy always" flag in the properties)
That's all .. simple ? ;-)
JW