Search code examples
azurepowershellazure-pipelinesazure-pipelines-build-taskazure-yaml-pipelines

PowerShell Task not running the script in Azure Pipelines?


I have a powershell task that is used to run a script which involves creating azure resources (Example: Resource group, Azure Key Vault, Function App...). When the pipeline is being run and it arrives to the powershell task in the deploy stage, it shows the following message:

enter image description here

The problem here, it says Finishing:Powershell but it didn't execute the script and did not create any azure resource.

Here is a sample of the powershell script:

$vaultName = "key vault name"
$blobstorageName = "blob storage name"
$Location = "Location Name"
$resourceGroupName = "Resource Group Name"

try {

    #Creation of Resource Group
    $resourceGroup = Get-AzResourceGroup -ResourceGroupName $resourceGroupName -ErrorAction SilentlyContinue 

    if($null -eq $resourceGroup)
    {
        New-AzResourceGroup -Name $resourceGroupName -Location $Location
    }

    else
    {
        Write-Host "The ResourceGroup with the name: $resourceGroupName already exists."
    }

    # Creation of Storage Account

    $checkBlobStorage = (Get-AzStorageAccountNameAvailability -Name $blobstorageName) | Select-Object NameAvailable
    if ($checkBlobStorage.NameAvailable)
    {
        New-AzStorageAccount -ResourceGroupName $resourceGroupName -AccountName $blobstorageName -Location $Location -SkuName Standard_LRS -Kind StorageV2 -AccessTier Hot
    }

    else 
    {
        Write-Host "The name $blobStorageName is not available. Suggest a new globally unique name!"
    }


catch 
{

}

Does anyone have a clue what is wrong ? Am I missing something in the powershell script (Maybe I don't have direct access to the azure portal from azure devops) or maybe something is missing in the Yaml file ?


Solution

  • Two major issues:

    1. you seem to be using the Powershell Task, which is not designed for communication with Azure. You should use the Azure Powershell task for this kind of script, because it already has the right modules loaded and the authentication prepared.
    2. your script is swallowing the error so it is hiding what went wrong. It's usually more useful not to catch exceptions; if your script is erroring then let it error, and let the pipeline show you in its log what has happened.