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
Anduin
In bash,
Create is not exist
is much easier!Just grep from the tsv output. No JSON required.
Long live Bash!
mma
新手自学.net core,遇到问题望指点。 点击重新生成解决方案后,控制台就停留在“已启动还原操作”,整个solution就像被frozen住了一样,什么都不能操作 14>------ 已启动全部重新生成: 项目: Moonglade.Web, 配置: Debug Any CPU ------ 14> 14>Bundler: Cleaning output from bundleconfig.json 14>Bundler: Done cleaning output file from bundleconfig.json 14> 14>已启动还原操作...
Nono
Another option for 1-liner lovers: