Search code examples
powershellazure-devopsazure-service-fabric

Service Fabric Start-ServiceFabricApplicationUpgrade - How to make powershell wait for successful upgrade before continuing


I am converting away from using the Azure devops pipeline "Upgrade Service Fabric Application" task and replacing it with a pure PowerShell approach.

Start-ServiceFabricApplicationUpgrade -ApplicationName fabric:/$(ServiceFabricApplicationName) -ApplicationTypeVersion $BuildNumber -ApplicationParameter $settings -Monitored -FailureAction Rollback

The issue is that when I use the devops pipeline task, it waits for the upgrade to complete and shows output in the console window. When I use my custom powershell, it executes immediately and moved to the next pipeline task even though in my cluster I can see the upgrade just got started. How can I make it show output and wait for success before it moves on?


Solution

  • This command Get-Service Fabric Application Upgrade will get the status of a Service Fabric application upgrade, so we can use it in the following PowerShell script to get the result of this upgradation.

    ## Start monitored application upgrade
    try
    {
        Write-Host "Start upgrading application..." 
        Start-ServiceFabricApplicationUpgrade -ApplicationName fabric:/$(ServiceFabricApplicationName) -ApplicationTypeVersion $BuildNumber -ApplicationParameter $settings -Monitored -FailureAction Rollback
    }
    catch
    {
        Write-Host ("Error starting upgrade. " + $_)
    
        Write-Host "Unregister application..."
        Unregister-ServiceFabricApplicationType -ApplicationTypeName fabric:/$(ServiceFabricApplicationName) -ApplicationTypeVersion $BuildNumber -Force
        throw
    }
    
    do
    {
        Write-Host "Waiting for upgrade..."
        Start-Sleep -Seconds 3
        $upgradeStatus = Get-ServiceFabricApplicationUpgrade -ApplicationName fabric:/$(ServiceFabricApplicationName)
    } while ($upgradeStatus.UpgradeState -ne "RollingBackCompleted" -and $upgradeStatus.UpgradeState -ne "RollingForwardCompleted" -and $upgradeStatus.UpgradeState -ne "Failed")
        
    if($upgradeStatus.UpgradeState -eq "RollingForwardCompleted")
    {
        Write-Host "Upgrade completed successfully."
    }
    elseif($upgradeStatus.UpgradeState -eq "RollingBackCompleted")
    {
        Write-Error "Upgrade was Rolled back."
    }
    elseif($upgradeStatus.UpgradeState -eq "Failed")
    {
        Write-Error "Upgrade Failed."
    }
    

    Therefore, this PowerShell task will wait for the result of this upgradation before it moves to the next pipeline task.