Home > front end >  How to check if azure resource exists in PowerShell?
How to check if azure resource exists in PowerShell?

Time:12-23

I am trying to check if an azure key vault already exists in a resource group using PowerShell. If the vault with the same name already exists even in the deleted state I only want to receive a user friendly message saying Key Vault already exists or catch the exception if there is any. I don't want the terminal to blow up with errors. If the key vault does not exist I want to create a new keyvault.

I have the following code:

$KeyVaultName = "Key Vault Name"
$ResourceGroupName = "Resource group name"

$KeyVault = Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $ResourceGroupName -ErrorAction SilentlyContinue

if($null -eq $KeyVault){
    New-AzKeyVault -ResourceGroupName $ResourceGroupName -VaultName $KeyVaultName -Location "Switzerland North"
}
else{
    Write-Host "$KeyVaultName already exists"
}

After executing the code I am getting this error message on the terminal:

New-AzKeyVault : A vault with the same name already exists in deleted state. You need to either recover or purge existing key vault.

I also tried using the following code as well:

if (!(Test-AzureName -Service $KeyVaultName))
{  
    New-AzKeyVault -ResourceGroupName $ResourceGroupName -VaultName $KeyVaultName -Location "Switzerland North" 
}

It gives me the following error after execution:

Test-AzureName : No default subscription has been designated. Use Select-AzureSubscription -Default to set the default subscription.

Though I only have one subscription being used.

Can someone please tell me if I am doing something wrong here ? Can you please provide me with an efficient way to achieve this ?

CodePudding user response:

You can try something like the following:

$KeyVaultName = "keyvaultname"
$ResourceGroupName = "resourcegroupname"
$KeyVaultLocation = "keyvaultlocation"
$KeyVault = Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $ResourceGroupName -ErrorAction SilentlyContinue

if($null -eq $KeyVault){
    $KeyVault = Get-AzKeyVault -VaultName $KeyVaultName -Location $KeyVaultLocation -InRemovedState -ErrorAction SilentlyContinue
    if ($null -eq $KeyVault) {
      New-AzKeyVault -ResourceGroupName $ResourceGroupName -VaultName $KeyVaultName -Location $KeyVaultLocation
    } else {
      Write-Host "$KeyVaultName exists but is in soft-deleted state"
    }
}
else{
    Write-Host "$KeyVaultName already exists"
}

Essentially what we are doing here is first checking if the Key Vault exists and is in active state. If we do not find any Key Vault, then we are checking if the Key Vault is in soft deleted state. If no results are found, then we are proceeding with creation of new Key Vault.

However, please note that Key Vault name is globally unique so it is quite possible that your New-AzKeyVault Cmdlet fails.

  • Related