Azure CLI how to check if a resource exists Azure CLI how to check if a resource exists azure azure

Azure CLI how to check if a resource exists


This should work in bash script:

if [ $(az group exists --name $RESOURCEGROUPNAME) = false ]; then    az group create --name $RESOURCEGROUPNAME --location $LOCATIONfi


In a bash script how can I check that a resource already exists so I don't try to create it again?

We can use CLI 2.0 command az group exists to test the resource group exist or not, like this:

C:\Users\user>az group exists -n jasontestfalse

In this way, before we create it, we can test the name available or not. In new resource group, we can create new Vnet and other resources.

For now, there is no CLI 2.0 command to test other resource exist or not. If you want to create resource in an existing resource group, maybe we should use CLI 2.0 command to list the resources, and use bash to make sure the resource exist or not.


You can use JMESPath queries to do this. All resource types support this, AFAIK.

For example, for VMs:

az vm list --resource-group $RESOURCEGROUPNAME --query "[?name=='$VMNAME'] | length(@)"

This will output the number of matching VMs - either 1 or 0.

You can use this to create if/else logic in bash as follows.

if [[ $(az vm list --resource-group $RESOURCEGROUPNAME --query "[?name=='$VMNAME'] | length(@)") > 0 ]]then  echo "VM exists"else  echo "VM doesn't exist"fi