Azure CLI can help us automate the configuration and management tasks of Azure. Ideally, for repetitive tasks, using CLI scripts can help us save time. However, Azure CLI still has some features that are not convenient enough, such as checking the existence of resources.

Current Situation


For some resource types, such as Resource Group, Azure CLI provides exists directive that can return the existence of a resource. For example, our script can determine whether a resource group exists before creating it:

$rsgExists = az group exists -n $rsgName
if ($rsgExists -eq 'false') {
    az group create -l $regionName -n $rsgName
}

However, not every Azure resource provides the exists directive. Up to the latest version of 2.1 CLI, where App Service Plan does not have exists directive:

Workaround


Now that Azure CLI doesn't provide native exists support for some resource types, we can only make our own, use the commands we have to find the resource by name, and check whether the number of returned results is greater than zero to determine whether the resource exists.

In the case of Windows PowerShell, executing az appservice plan list lists all the App Service Plan under your current subscription. And you can filter the App Service Plan by criteria, such as by name:

az appservice plan list --query "[?name=='moonglade-test-plan']"

For non-exist App Plan, the result is empty:

az appservice plan list --query "[?name=='work996']"

The return format of the Azure CLI is a JSON string, it needs to be converted to an object before it can be recognized by PowerShell for subsequent actions. Fortunately, PowerShell comes with a very convenient conversion method: ConvertFrom-Json

Thus, we can determine whether an App Service Plan exists by checking whether the returned array object length is greater than zero:

Note that True and False are the real Boolean types here, while the exists command that comes with Azure CLI returns a string of 'true' or 'false'. So here, we can use if statement to check this real Boolean type, rather than using -eq to check string equality as before. My actual code is as follows:

$planCheck = az appservice plan list --query "[?name=='$aspName']" | ConvertFrom-Json
$planExists = $planCheck.Length -gt 0
if (!$planExists) {
    az appservice plan create -n $aspName -g $rsgName --sku S1 --location $regionName
}

Reference: https://github.com/Azure/azure-cli/issues/6442#issuecomment-392963887