Thursday, April 28, 2011

Azure startup tasks run EVERY time your Role instance boots

I have recently had a total “DUH!” moment.  I almost called this post “The Revenge of the Batch Script.”

Azure has this feature called startup tasks.  These are task that run when your Roles instances boot.  And all the examples define these as command files (“.cmd” that is).  Okay, easy enough.

For some strange reason I have been stuck in the thinking that These run at instance provisioning; just after publishing my service.  As in these are RunOnce tasks.  But they actually run at the booting of an instance.  In fact they run anytime that any particular role instance boots.

It took me messing around with writing every single little thing to log files to really understand this.  And I also had to reboot my Azure Role instances when I was RDP’d into them.

What this really boils down to is that all those examples that you read about startup tasks where they mention to use them to install software; they are totally over simplified.  Your script needs to have some smarts, it needs to know if it ran before.  Because installing over a configured install doesn’t always work.  Reregistering a COM objects, doesn’t always work.

Oh, and if you use Azure Connect and define a an AD domain join – your VM will reboot as part of that domain join.  It is this precise thing that brought me here in the first place.

Here is my example of a startup task script with some very simple intelligence:

IF NOT EXIST %Public%\Documents\completedSetup.txt goto 20
ECHO The file completedSetup.txt exists.  Exiting..
GOTO END

:20
ECHO The file completedSetup.txt does not exist.  Setting up MyApp..

Perform all of my complicated application installation sequencing here..

Here I setup a task and execute it.  It is a PowerShell script that does my heavy lifting.  When it finishes it writes out the file that I am looking for.

:END
REM send a clean exit code
exit /b 0

Now, the key part lies in my PowerShell script.  At the end of my PowerShell script is:

Out-File $env:Public\Documents\completedSetup.txt

Something really simple, a little flag file, right where any user security context can find it.

2 comments:

Anonymous said...

Thanks for this, I was actually looking for the existence of startup tasks, but this will save me headaches.

Anonymous said...

Thanks for this, I was actually looking for the existence of startup tasks, but this will save me headaches.