Azure CLI how to check if a resource exists - azure

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

This should work in bash script:
if [ $(az group exists --name $RESOURCEGROUPNAME) = false ]; then
az group create --name $RESOURCEGROUPNAME --location $LOCATION
fi

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 jasontest
false
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

If a resource show command returns an empty string and a success status code (0), then the resource does not exist.
Edit: ChrisWue pointed out that this is no longer true. It must have changed since I left the Azure CLI team (it used to be a requirement that all commands worked like this). Or it may be that there is a bug for the key vault commands he mentioned below.

this work for my batch commands
call az webapp show --subscription <yoursubs> --resource-group <yourrg> --name <yourappname> -query name
if %errorlevel% == 1 (
az webapp create ...
)

As mentioned in another answer - there is no generic "exists" command. One line of reasoning I've found was that "create" is meant to be idem potent - therefor if you have a script that creates resources (for example as part of a build pipeline) it doesn't matter how often you execute it since "it will do the right thing".
If you still need to do this you can do it in shell like this (the example is for keyvault but it should work for all resource types that have a show command)
if az keyvault show -n my-keyvault -o none; then
echo "keyvault exists"
else
echo "keyvault doesn't exist"
fi
It should be noted that az will output an error message to stderr if the resource doesn't exists - this doesn't affect the check but if it bothers you then you can redirect stderr to /dev/null
In our case we needed this because we don't run the infra scripts if the setup hasn't changed (cuts our build time in half). We dectect this by creating a hash of the infra-scripts and store it in a keyvault. When the script runs it creates the keyvault (to make sure it exists) and then tries to check the secret that contains the hash. If the hash is still the same then don't run the rest of the script.
Catch is that keyvault create nukes the access policies which also includes the web-app managed identity access policy which won't get added if the rest of the script doesn't run ... so the fix is to check if the keyvault exists first and to not create it if it does.

Related

az cil vnet --dns-servers

I have a problem with using --dns-servers flag in az cli.
When I try to update more than one DNS server it gets broken
az network vnet update \
--name $VNET_name \
--subscription $SUBSCRIPTION \
--resource-group $RGRP_name \
--dns-servers "${LOCATION[3]} ${LOCATION[4]}"
the output:
IP address is not valid '0.0.0.1 0.0.0.2'
The MS documentation says:
--dns-servers
Space-separated list of DNS server IP addresses.
You can try with something like below which I tested in my environment :
$LOCATION = #(
'10.0.0.1',
'10.0.0.2',
'10.0.0.3',
'10.0.0.4'
)
$VNET_name="ansuman-vnet"
$SUBSCRIPTION = "<SubscriptionId>"
$RGRP_name="ansumantest"
az network vnet update --name $VNET_name --subscription $SUBSCRIPTION --resource-group $RGRP_name --dns-servers $LOCATION[2,3]
Output:
Your DNS IP addresses '0.0.0.1 0.0.0.2' are not usable as a real IP addresses.
IANA states that 0.0.0.0/8 (0...) is reserved as a source address only. You can get into situation where it appears you have this address but that's normally because no address has been assigned to you (by DHCP, for example).
See also Wikipedia entry on IPv4.
Try to set real --dns-servers like 8.8.8.8
Is 0.0.0.0 a valid IP address?
ok, figured it out somehow.
if you use those vars stright away without closing them withing quotation marks it all works
. ./location_arrays
declare -n LOCATION='EM21'
...
az network vnet create \
--name $VNET_name \
--subscription $SUBSCRIPTION \
--resource-group $RGRP_name \
--location ${LOCATION[2]} \
--dns-servers ${LOCATION[-2]} ${LOCATION[-1]}

Run statement with multiple lines in azure cli

I am new to ARM templates and Azure CLI
This may seem a really stupid question, but I am using the tutorial here
It contains the following command
templateFile="my template file"
az deployment group create \
--name blanktemplate \
--resource-group myResourceGroup \
--template-file $templateFile
I am running Azure Cli via a command prompt
How can I run this? As there are multiple lines
Paul
Replace the backslashs ( \ ) with backticks ( ` ) at the end of each line and you should be able to run it. Your sample code with the backticks:
templateFile="my template file" `
az deployment group create `
--name blanktemplate `
--resource-group myResourceGroup `
--template-file $templateFile
for example, the following code will execute in the cloud shell if you just copy paste
Write-Host `
Hello, `
World!
There's another way. You can create a temporary PowerShell script file in cloud shell. Paste all the commands there as necessary and run the script file from the cloud shell.

Assign current AKS resource and name to linux variables

I am running a script that requires the resource group and name of current AKS client config. Previously configured with az aks get-credentials ...
Current script:
(I type AKS=something and RG=SOMETHING before running)
az aks update -g $RG -n $AKSNAME ...
Wanted script:
(I type nothing before running)
AKSNAME=$(what goes here?)
RG=$(what goes here?)
az aks update -g $RG -n $AKSNAME ...
How can I load RG and AKSNAME values automatically through a shell script?
EDIT: I current assign the values to those variables by hand. I want the script to find the values automatically, corresponding to the cluster in the current context e.g. which kubectl is using.
If you just get the credential via the command az aks get-credentials .... without parameter --admin, then you can get the cluster name like this:
AKSNAME=$(kubectl config current-context)
And if you use the parameter --admin, then you need to change the command like this:
AKSNAME=$(kubectl config view --minify -o jsonpath='{.contexts[0].context.cluster}')
Then you can get the group name like this:
RG=$(az aks list --query "[?name == '$AKSNAME'].resourceGroup" -o tsv)

azure cli list nic attached to VM

I am working on bash shell. I need az cli or unix script to find out NIC name attached to particular VM. I know VM name and VM Resource Group Name and my Target is to findout out which NIC is attached to this VM and which resouce group this NIC belongs to?
Please follow this line of azure cli code:
Step 1: Define a variable, like a. Note that there is no whiteSpace around the chars = :
a="$(az vm nic list --resource-group "your_resource_group" --vm-name "your_vm_name" --query "[].{id:id}" --output tsv)"
Step 2: Just get the nic name and it's resource group:
az vm nic show -g "your_resource_group" --vm-name "your_vm_name" --nic $a --query "{name:name,resourceGroup:resourceGroup}" --output table
Step 3: If you want get all the information of nic, please use the code below:
az vm nic show -g "your_resource_group" --vm-name "your_vm_name" --nic $a
az vm nic list --resource-group
--vm-name
[--subscription]
This will list all nics on a vm.
eg. az vm nic list -g MyResourceGroup --vm-name MyVm

How can I retrieve Azure scale set's VM private IP Addresses via terraform?

I'm wondering how can I retrieve scale set VM's private IP address with Terraform-provider-azurerm. I think there are no resources nor data resources directly return VM IP's.
One option I tried was generate shellscript via template resource.
# get_vmss_privateip.tpl
#!/bin/bash
cap=`az vmss show \
--resource-group ${resource_group} \
--subscription ${subscription} \
--name ${name} \
--query 'sku.capacity'`
for i in `seq 1 $cap`
do
az resource show \
--resource-group ${resource_group} \
--resource-type Microsoft.Compute/virtualMachineScaleSets \
--api-version 2017-03-30 \
--name ${name}/virtualMachines/$i/networkInterfaces \
--query 'value[0].properties.ipConfigurations[0].properties' \
| jq -c '{privateIPAddress}'
done
then run terraform to generate sh.
data "template_file" "private_ip_scripts" {
template = "${file("templates/get_vmss_privateip.tpl")}"
vars {
resource_group = "${data.azurerm_resource_group.current.name}"
subscription = "${data.azurerm_subscription.current.subscription_id}"
name = "${azurerm_virtual_machine_scale_set.test.name}"
}
}
resource "local_file" "test_private_ip_scripts" {
filename = "scripts/get_vmss_instance_private_ip.sh"
content = "${data.template_file.manage_private_ip_scripts.rendered}"
}
But this approach is too far from goal, and I do want to use private IP's in the terraform, not outside terraform.
Do anyone have much better ideas?
EDIT 2018/11/2
I've done via external data resource.
data "external" "vmss_test_private_ip" {
program = ["bash", "${local_file.test_private_ip_scripts.filename}"]
}
output hoge {
value = "${data.external.vmss_test_private_ip.result}"
}
This type of resource can be imported into TF Scale Set. So this is one option, only hassle is there are a lot of attributes and importing introduces other issues. I've found one or two things that aren't exposed as data resources in the AzureRM provider. Might be worth adding a request to the GitHub repo?
Regards,

Resources