Azure CLI how to check if a resource exists

Jeremy picture Jeremy · Sep 28, 2017 · Viewed 8.8k times · Source

I'm starting to write a bash script to provision a VM in a new or existing resource group so that we can enforce naming convention and configuration.

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

#1. If a new resource group is desired, create it now.  Microsoft Docs
az group create --name $RESOURCEGROUPNAME --location $LOCATION


#2. Create a virtual network and subnet if one has not already been created.  Microsoft Docs
#   Consider a separate VNet for each resource group. 
#   az network vnet list -output table
az network vnet create \
--resource-group $RESOURCEGROUPNAME \
--name $RESOURCEGROUPNAME-vnet \
--address-prefix 10.0.x.0/24 \
--subnet-name default \
--subnet-prefix 10.0.x.0/24


#x is the next available 3rd octet value


#3. Create a public IP Address.  Microsoft Docs
az network public-ip create \
--resource-group $RESOURCEGROUPNAME \
--name $VMNAME-ip \
--dns-name $DNSNAME


#4. Create a network security group.  Microsoft Docs
az network nsg create \
--resource-group $RESOURCEGROUPNAME \
--name $VMNAME-nsg 


#5. Create a rule to allow SSH to the machine.  Microsoft Docs
az network nsg rule create \
--resource-group $RESOURCEGROUPNAME \
--nsg-name $VMNAME-nsg \
--name allow-ssh \
--protocol tcp \
--priority 1000 \
--destination-port-range 22 \
--access allow


#6. Create a virtual NIC.   Microsoft Docs
az network nic create \
--resource-group $RESOURCEGROUPNAME \
--name $VMNAME-nic \
--vnet-name $RESOURCEGROUPNAME-vnet \
--subnet default \
--public-ip-address $VMNAME-ip \
--network-security-group $VMNAME-nsg



#7. Create an availability set, if redundancy is required.  Microsoft Docs
az vm availability-set create \
--resource-group $RESOURCEGROUPNAME \
--name $AVSETNAME-as


#8. Create the VM. Microsoft Docs
az vm create \
--resource-group $RESOURCEGROUPNAME \
--location $LOCATION \
--name $VMNAME \
--image UbuntuLTS \
--size $VMSIZE \
--availability-set $AVSETNAME-as \
--nics $VMNAME-nic \
--admin-username $ADMINUSERNAME \
--authentication-type ssh
--ssh-key-value @$SSHPUBLICKEYFILE \
--os-disk-name $VMNAME-osdisk

Answer

Yuhis picture Yuhis · Jun 11, 2019

This should work in bash script:

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