隨著雲端運算漸漸普及,愈來愈多的企業開始評估與使用Microsoft Azure,而Azure Web Apps (Standard/Premium)與Azure Cloud Services提供的Production Slot 與 Staging Slot 切換功能讓我們在更新網站內容時減少停機時間。但是,因某些因素(如:資料保護規定)而必需使用企業內部署的IIS來做為Web Site時怎麼辦?我們可以使用Windows PowerShell來達成。
首先,我們應該在IIS中有一個正式服務用戶的站台(Production Slot,在本文的範例中站台名稱為Default Web Site,繫結在 www.uuu.local),以及一個用於更新內容與測試用的站台(Staging Slot,在本文的範例中站台名稱為 Staging,繫結在 staging.uuu.local)。
更改站台的實體路徑並不是一個好的方式,因為還有應用程式集區、應用程式、虛擬目錄等也要一併切換;而單獨更改站台的繫結雖然可行,但卻會造成後續維護與站台紀錄混淆的問題。因此,建議,至少應同時更改站台繫結、站台名稱與站台ID這三個項目。就讓我們來做個Swap-IIS-Slots.ps1吧!
Swap-IIS-Slots.ps1的指令碼如下:
$ProductionSiteName="Default Web Site"
$StagingSiteName="Staging"
$tempid=25149191
$now=Get-Date
Import-Module WebAdministration
Stop-WebSite $ProductionSiteName
Stop-WebSite $StagingSiteName
$production=(Get-ItemProperty IIS:\Sites\$ProductionSiteName).Bindings
$staging=(Get-ItemProperty IIS:\Sites\$StagingSiteName).Bindings
$productionid=(Get-ItemProperty IIS:\Sites\$ProductionSiteName).id
$stagingid=(Get-ItemProperty IIS:\Sites\$StagingSiteName).id
Set-ItemProperty IIS:\Sites\$ProductionSiteName -Name "id" -Value $tempid
Clear-ItemProperty IIS:\Sites\$ProductionSiteName -Name bindings
Set-ItemProperty IIS:\Sites\$StagingSiteName -Name "id" -Value $productionid
Set-ItemProperty IIS:\Sites\$StagingSiteName -Name bindings -Value $production
Set-ItemProperty IIS:\Sites\$ProductionSiteName -Name "id" -Value $stagingid
Set-ItemProperty IIS:\Sites\$ProductionSiteName -Name bindings -Value $staging
Rename-Item IIS:\Sites\$ProductionSiteName temp
Rename-Item IIS:\Sites\$StagingSiteName $ProductionSiteName
Rename-Item IIS:\Sites\temp $StagingSiteName
iisreset
Write-Host ("切換共使用:" + ((Get-Date) - $now).TotalSeconds +" 秒.")`
-ForegroundColor "Yellow"
切換前,我們以 Invoke-WebRequest對http://www.uuu.local發出要求,得到Web Site 1,以Get-WebSite得知實體路徑是在wwwroot,接著執行Swap-IIS-Slots.ps1,數秒鐘之後即已切換完成。
切換完成後,我們再以Invoke-WebRequest仍對http://www.uuu.local發出要求,得到 Web Site 2,以Get-WebSite得知實體路徑是在wwwroot2。
您可在下列課程中了解更多技巧喔!
相關學習資源
【UIIS85】Windows Server 2012 R2 IIS 8.5建置與管理