Thursday, August 25, 2011

Duplicating an IIS application in Azure with PowerShell

I have a need to add an additional application pool into IIS in my Azure Web Role.

The requirements from the developer are:

  1. I copy an existing application folder under IIS to a new folder.
  2. I turn this copy of the folder into an application.
  3. I add this application to the same application pool of the application I am copying.

I knew what I needed to do.  It can be done straight through the IIS administration console and Explorer.  Find the physical location of the IIS site, copy the folder, then in IIS right click the folder and convert to an application, selecting the existing application pool.  Sounds easy enough.  But scripting it was not that straightforward, or was it..

First, this is an Azure Web Role – no “Default Web Site” happening here.  Second, I have an installer that is creating site I am duplicating.  Third, I have an entire folder of IIS files to copy.

Begin with adding the Azure Service Runtime snap-in and importing the IIS PowerShell module.  And get information about the role where this script is running (we need that later).

Import-Module WebAdministration

add-pssnapin microsoft.windowsazure.serviceruntime

$role = Get-RoleInstance –Current

I have variables that I am passing in that will be Virtual Directory paths (note the foreslash).

$auth_virtual_path = "/MyApp/Authentication"
$fed_virtual_path = "/MyApp/FederatedIdentity"

Get the site object through the provider.  I get it this way because I need the PSPath attribute later on.

$site = Get-ChildItem IIS:\sites | where {$_.Name -match ($role.id)}

I mentioned there is no default web site, instead it is named with the Role Instance Id.

I now work through where IIS created the physical location of the default web site and stuck my virtual paths.  This is Azure, no assumptions as to where things might happen.

$authSitePath = (($site.PhysicalPath) + $auth_virtual_path) -replace "/", "\"
"The physical path of " + $auth_virtual_path + " is:  " + $authSitePath
$fedSitePath = (($site.PhysicalPath) + $fed_virtual_path) -replace "/", "\"
"The physical path of " + $fed_virtual_path + " will be:  " + $fedSitePath

Copy the original folder and contents to the new folder.

Copy-Item $authSitePath -destination $fedSitePath –recurse

Get the existing web application because I need to assign my copy to the same application pool.

$authApp = Get-WebApplication | where {$_.Path -match $auth_virtual_path}

Create the string for the new PSPath location.

$fedAuthPsPath = (($site.PSPath) + $fed_virtual_path) -replace "/", "\"

Convert the folder that I copied into an application and add it to the existing application pool.

ConvertTo-WebApplication -ApplicationPool $authApp.applicationPool -PSPath $fedAuthPsPath

That is it. 

No comments: