2

I'm running this PowerShell script twice, almost simultaneously:

#Provision Resource Group and all Resources within ARM Template
New-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName `
-TemplateFile $TemplateFile `
-Mode Incremental `
-TemplateParameterFile $TemplateParametersFile @ExtraParameters `
-keyVaultAccessPolicies @($keyVaultPoliciesList) `
-Force

Which throws this exception:

VERBOSE: 16:48:48 - Template is valid.
New-AzureRmResourceGroupDeployment : Unable to edit or replace deployment 'DeploymentTemplate': previous deployment from '5/18/2017 2:48:47 PM' is still active (expiration time is '5/25/2017 2:48:46 PM'). Please see https://aka.ms/arm-deploy for usage details.
At L:\Source\Start-ArmEnvironmentProvisioning.ps1:274 char:1
+ New-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupN ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [New-AzureRmResourceGroupDeployment], CloudException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.NewAzureResourceGroupDeploymentCmdlet

I need to avoid 2 deployments were running at the same time to the same resource. So, I'm trying to catch the exception and then later force to run the AzureRM provisioning sequentially.

Try
{
  #Provision Resource Group and all Resources within ARM Template
  $params = @{'Name' = $ResourceGroupName;
              'ResourceGroupName' = $ResourceGroupName;
              'TemplateFile' = $TemplateFile;
              'TemplateParameterFile' = $TemplateParametersFile;
              'keyVaultAccessPolicies' = @($keyVaultPoliciesList) }
  New-AzureRmResourceGroupDeployment @params -Force
}
Catch
{
  $ErrorMessage = $_.Exception.Message
  $FailedItem = $_.Exception.ItemName
  Write-Error "We failed to read file $FailedItem. The error message was $ErrorMessage"
  Break
}

However, I had no success so far. I'm new to PowerShell scripting.

1
  • 3
    What about adding -ErrorAction Stop to your command?
    – BenH
    Commented May 18, 2017 at 15:32

1 Answer 1

12

The error thrown by New-AzureRmResourceGroupDeployment is Non-Terminating and will not trigger a Try{}catch{} statement as is.

By adding -ErrorAction Stop to the end of the Statement inside the Try block (before or after the -Force), you can force it to become a terminating error, which will trigger the Catch statement.

1
  • -whatif flag helps if you want to check the script before actually running it. dry-run flag (at least now, not sure when it was introduced) Commented May 2, 2022 at 22:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.