What is Azure CLI?
The Azure Command-Line Interface (CLI) is a cross-platform command-line tool that allows you to manage Azure resources from the command line. With the Azure CLI, you can create, manage, and delete Azure resources, such as virtual machines, storage accounts, and databases. You can also use the Azure CLI to run scripts to automate Azure tasks.
The Azure CLI is available to install in Windows, macOS and Linux environments. It can also be run in a Docker container and Azure Cloud Shell.
The current version of the Azure CLI is 2.54.0.
Install Azure CLI on Windows
# Download and Install Interactive
Download Link - https://aka.ms/installazurecliwindowsx64
# Using Command line with Powershell
# To install the Azure CLI using PowerShell, start PowerShell as administrator and run the following command:
$ProgressPreference = 'SilentlyContinue'; Invoke-WebRequest -Uri https://aka.ms/installazurecliwindows -OutFile .\AzureCLI.msi; Start-Process msiexec.exe -Wait -ArgumentList '/I AzureCLI.msi /quiet'; Remove-Item .\AzureCLI.msi
# You can also use winget, Microsoft's Package manager for Windows, to install and manage updates for Azure CLI.
winget install -e --id Microsoft.AzureCLI
Install the Azure CLI on Linux
The CLI requires the following software:
Python 3.6.x, 3.7.x or 3.8.x.
libffi
OpenSSL 1.0.2
$ curl -L https://aka.ms/InstallAzureCli | bash
How to run the Azure CLI in a Docker container?
$ docker run -it mcr.microsoft.com/azure-cli

FAQ of Azure CLI
What advantage is there to using Azure CLI? | You can manage multiple Azure resources concurrently from a flexible command-line. For example, create 50 Azure storage accounts, or update multiple user permissions through a script. |
Where can I run the Azure CLI? | The Azure CLI runs in Windows (Cmd or PowerShell), Linux, macOS, Docker containers, and Azure Cloud Shell. Using Azure Cloud Shell is the quickest way to get started. |
Do I have to install the Azure CLI? | Azure Cloud Shell and some Linux distributions have the Azure CLI preinstalled. For all other environments, you must install the Azure CLI. |
How do I run the Azure CLI in a Docker container? | docker run -it mcr.microsoft.com/azure-cli |
What URLs do I need for proxy bypass? | This depends on the Cloud you are using. For a complete list see the list of endpoints needed for proxy bypass. |
How do I sign in? | Use az login inside your console window. Use your own Azure username and password, a service principal, managed identity or WAM. |
Using reference commands
Question | Answer |
---|---|
What is the Azure CLI syntax pattern? | “command group + command subgroup + command + –parameters” Example: “az storage account create –name myStorageAccount” |
What is the difference between a command group, cmdlet, command, alias, module, and reference? | Good question! The Azure CLI only has command groups, reference commands, and user-defined aliases. You may be thinking of Azure PowerShell if you are looking for cmdlets and modules. |
What is an extension and why does it have to be installed separately? | Extensions are command group add-ins that are not shipped as part of the core Azure CLI. You are prompted to install an extension the first time you use it. Get a list of available extensions by running az extension list-available -output table . |
How do I get a list of all commands, both core and extension? | For a list of command groups, in your console type az and Enter. For a list of subgroups and commands, use the --help parameter. Example: az account --help or az account subscription --help outputs a command list for just the group or subgroup. |
Does the Azure CLI have tab completion? | Yes! When typing a command in PowerShell, press your Tab key. This feature is only available in PowerShell. |
How do I get in-line help? | Every command has a --help parameter that results in descriptions and tips to display in your console. Example: az account ---help or az vm create --help |
How can I learn to use multiple reference commands to complete a single job to be done? | We’re glad you asked! The Azure CLI provides several interactive commands that provide syntax and next steps. In the next section, learn about az interactive , az scenario , az next , and az find . |
Learning Azure CLI
There are several reference commands that provide interactive prompts to help you learn the Azure CLI.
Command | Description | Example |
---|---|---|
az interactive | In a PowerShell console, get auto-completion, command descriptions, and examples as you type. | See Work in interactive mode for more information. Example: Type az interactive in your console window then Enter. |
az scenario | Get end to end (E2E) examples and execute them with walk-through prompts. | Type az scenario guide "keywords of interest" in your console then Enter. The Azure CLI returns scenarios based on your keyword(s). Example: az scenario guide "virtual machines" |
az next | Get recommendations for the next Azure CLI command based on customer execution patterns. You are prompted to select a command path. | Type az next in your console then Enter. Pick from 1 of 7 preset command paths. |
az find | This is an AI robot that will return reference examples for keywords. | Type az find "active subscription" in your console then Enter. |
Common usage questions
Question | Reference command answer |
---|---|
How do I know what subscription I’m using? | az account show --output table |
How do I change my subscription? | az account set --subscription "mySubscriptionName" |
How can I set a default resource group and location? | az config set defaults.location=westus2 defaults.group=MyResourceGroup |
How do I query command output? | az account show --query "{tenantId:tenantId,subscriptionid:id}" |
How do I format output from a command? | az account list --output table |
Can you help me to learn Bash with Azure CLI commands? | Absolutely! We all have different technical strengths, and for that reason, Microsoft offers a How-to guide for learning Bash. Enjoy! |
Azure CLI Command Reference and Cheat Sheet
Get a list of resources without a tag
az resource list --query "[?tags == null].{Name:name, Type:type}" --output table
Get a list of resources with a specific tag
az resource list --query "[$tags.environment = 'development'].{Name:name, Type:type}" --output table
Get a list of resources without a specific tag and exclude resources with missing tags
az resource list --query "[?tags.environment != 'development' && not_null(tags)]"
Setting defaults
Set default resource group
az config set defaults.group=<resource-group>
Set default subscription
az account set --subscription <subscription>
Common Azure CLI Commands List
1) Manage resource groups and template deployments:
COMMANDS | |
az group create | Create a new resource group. |
az group delete | Delete a resource group. |
az group deployment | Manage Azure Resource Manager deployments. |
az group deployment cancel | Cancels a currently running template deployment. |
az group deployment create | Start a deployment. |
az group deployment delete | Deletes a deployment from the deployment history. |
az group deployment export | Export the template used for deployment. |
az group deployment list | Get all the deployments for a resource group. |
az group deployment operation | Manage deployment operations. |
az group deployment operation list | Gets all deployments operations for deployment. |
az group deployment operation show | Get a deployment’s operation. |
az group deployment show | Gets a deployment. |
az group exists | Check if a resource group exists. |
az group list | List resource groups. |
az group lock | Manage Azure resource group locks. |
az group lock create | Create a resource group lock. |
az group lock delete | Delete a resource group lock. |
az group show | Gets a resource group. |
az group update | Update a resource group. |
2) Manage Linux or Windows virtual machines.
COMMANDS | |
az vm application | Manage applications for VM. |
az vm application list | List applications for VM. |
az vm application set | Set appliations for VM. |
az vm assess-patches | Assess patches on a VM. |
az vm auto-shutdown | Manage auto-shutdown for VM. |
az vm availability-set | Group resources into availability sets. |
az vm availability-set create | Create an Azure Availability Set. |
az vm availability-set delete | Delete an availability set. |
az vm availability-set list | List availability sets. |
az vm availability-set list-sizes | List VM sizes for an availability set. |
az vm availability-set show | Get information for an availability set. |
az vm availability-set update | Update an Azure Availability Set. |
az vm capture | Capture information for a stopped VM. |
az vm convert | Convert a VM with unmanaged disks to use managed disks. |
az vm create | Create an Azure Virtual Machine. |
az vm deallocate | Deallocate a VM. |
az vm delete | Delete a VM. |
az vm diagnostics | Configure the Azure Virtual Machine diagnostics extension. |
az vm disk | Manage the managed data disks attached to a VM. |
az vm disk attach | Attach a managed persistent disk to a VM. Please note that –ids only supports one disk. |
az vm disk detach | Detach a managed disk from a VM. |
az vm encryption | Manage encryption of VM disks. |
az vm encryption show | Show encryption status. |
az vm extension | Manage extensions on VMs. |
az vm extension image list-versions | List the versions for available extensions. |
az vm get-instance-view | Get instance information about a VM. |
az vm host | Manage Dedicated Hosts for Virtual Machines. |
az vm host create | Create a dedicated host. |
az vm host delete | Delete a dedicated host. |
az vm identity | Manage service identities of a VM. |
az vm identity assign | Enable managed service identity on a VM. |
az vm identity remove | Remove managed service identities from a VM. |
az vm identity show | Display VM’s managed identity info. |
az vm image list-skus | List the VM image SKUs available in the Azure Marketplace. |
az vm list | List details of Virtual Machines. |
az vm list-ip-addresses | List IP addresses associated with a VM. |
az vm list-sizes | List available sizes for VMs. |
az vm list-skus | Get details for compute-related resource SKUs. |
az vm list-usage | List available usage resources for VMs. |
az vm list-vm-resize-options | List available resizing options for VMs. |
az vm monitor | Manage monitor aspect for a vm. |
az vm nic | Manage network interfaces. See also az network nic. |
az vm nic add | Add existing NICs to a VM. |
az vm nic list | List the NICs available on a VM. |
az vm open-port | Opens a VM to inbound traffic on specified ports. |
az vm redeploy | Redeploy an existing VM. |
az vm repair | Auto repair commands to fix VMs. |
az vm resize | Update a VM’s size. |
az vm restart | Restart VMs. |
az vm secret | Manage VM secrets. |
az vm secret add | Add a secret to a VM. |
az vm secret format | Transform secrets into a form that can be used by VMs and VMSSes. |
az vm secret list | List secrets on a VM. |
az vm secret remove | Remove a secret from a VM. |
az vm start | Start a stopped VM. |
az vm stop | Power off (stop) a running VM. |
az vm update | Update the properties of a VM. |
az vm user | Manage user accounts for a VM. |
az vm user delete | Delete a user account from a VM. |
az vm user reset-ssh | Reset the SSH configuration on a VM. |
az vm user update | Update a user account. |
az vm wait | Place the CLI in a waiting state until a condition of the VM is met. |
3) Manage storage accounts.
COMMANDS | |
az storage account check-name | Check that the storage account name is valid and is not already in use. |
az storage account create | Create a storage account. |
az storage account delete | Delete a storage account. |
az storage account encryption-scope | Manage encryption scope for a storage account. |
az storage account failover | Failover request can be triggered for a storage account in case of availability issues. |
az storage account file-service-properties | Manage the properties of file service in storage account. |
az storage account generate-sas | Generate a shared access signature for the storage account. |
az storage account keys | Manage storage account keys. |
az storage account list | List storage accounts. |
az storage account management-policy | Manage storage account management policies. |
az storage account network-rule | Manage network rules. |
az storage account or-policy | Manage storage account Object Replication Policy. |
az storage account or-policy create | Create Object Replication Service Policy for storage account. |
az storage account or-policy delete | Delete specified Object Replication Service Policy associated with the specified storage account. |
az storage account private-endpoint-connection | Manage storage account private endpoint connection. |
az storage account private-link-resource | Manage storage account private link resources. |
az storage account private-link-resource list | Get the private link resources that need to be created for a storage account. |
az storage account revoke-delegation-keys | Revoke all user delegation keys for a storage account. |
az storage account show | Show storage account properties. |
az storage account show-connection-string | Get the connection string for a storage account. |
4) Manage KeyVault keys, secrets, and certificates.
COMMANDS | |
az keyvault backup | Manage full HSM backup. |
az keyvault certificate | Manage certificates. |
az keyvault certificate create | Create a Key Vault certificate. |
az keyvault create | Create a Vault or HSM. |
az keyvault delete | Delete a Vault or HSM. |
az keyvault delete-policy | Delete security policy settings for a Key Vault. |
az keyvault key | Manage keys. |
az keyvault key backup | Request that a backup of the specified key be downloaded to the client. |
az keyvault key create | Create a new key, stores it, then returns key parameters and attributes to the client. |
az keyvault key decrypt | Decrypt a single block of encrypted data. |
az keyvault key delete | Delete a key of any type from storage in Vault or HSM. |
az keyvault key download | Download the public part of a stored key. |
az keyvault key encrypt | Encrypt an arbitrary sequence of bytes using an encryption key that is stored in a Vault or HSM. |
az keyvault key restore | Restore a backed up key to a Vault or HSM. |
az keyvault key rotate | Rotate the key based on the key policy by generating a new version of the key. |
az keyvault key rotation-policy | Manage key’s rotation policy. |
az keyvault key show | Get a key’s attributes and, if it’s an asymmetric key, its public material. |
az keyvault key show-deleted | Get the public part of a deleted key. |
az keyvault list | List Vaults and/or HSMs. |
az keyvault list-deleted | Get information about the deleted Vaults or HSMs in a subscription. |
az keyvault network-rule | Manage vault network ACLs. |
az keyvault recover | Recover a Vault or HSM. |
az keyvault restore | Manage full HSM restore. |
az keyvault restore start | Restore a full backup of a HSM. |
az keyvault role | Manage user roles for access control. |
az keyvault secret | Manage secrets. |
az keyvault secret backup | Backs up the specified secret. |
az keyvault secret list | List secrets in a specified key vault. |
az keyvault secret show | Get a specified secret from a given key vault. |
az keyvault storage | Manage storage accounts. |
az keyvault update | Update the properties of a Vault. |
5) Manage SQL servers.
COMMANDS | |
az sql server create | Create a server. |
az sql server delete | Deletes a server. |
az sql server dns-alias | Manage a server’s DNS aliases. |
az sql server firewall-rule | Manage a server’s firewall rules. |
az sql server firewall-rule create | Create a firewall rule. |
az sql server key | Manage a server’s keys. |
az sql server key create | Creates a server key. |
az sql server key show | Shows a server key. |
az sql server list | List available servers. |
az sql server list-usages | Returns server usages. |
az sql server outbound-firewall-rule | Manage a server’s outbound firewall rules. |
az sql server show | Gets a server. |
az sql server vnet-rule | Manage a server’s virtual network rules. |
az sql server vnet-rule create | Create a virtual network rule to allows access to an Azure SQL server. |
az sql server vnet-rule delete | Deletes the virtual network rule with the given name. |
az sql server vnet-rule list | Gets a list of virtual network rules in a server. |
Azure CLI 2.0 cheatsheet for Login, Resources, VMs, Resource groups, Storage, Batch, and Containers.
az login
az login -u myemail@address.com
az account list
az account set --subscription "xxx"
az account list-locations
az resource list
azure --version
azure help
az vm list-sizes --location eastus
az vm image list --output table
az vm create --resource-group myResourceGroup --name myVM --image ubuntults
az vm create --resource-group myResourceGroup --name myVM --image win2016datacenter
az group create --name myresourcegroup --location eastus
az storage account create -g myresourcegroup -n mystorageaccount -l eastus --sku Standard_LRS
az group delete --name myResourceGroup
az vm list
az vm start --resource-group myResourceGroup --name myVM
az vm stop --resource-group myResourceGroup --name myVM
az vm deallocate --resource-group myResourceGroup --name myVM
az vm restart --resource-group myResourceGroup --name myVM
az vm redeploy --resource-group myResourceGroup --name myVM
az vm delete --resource-group myResourceGroup --name myVM
az image create --resource-group myResourceGroup --source myVM --name myImage
az vm create --resource-group myResourceGroup --name myNewVM --image myImage
az vm extension list --resource-group azure-playground-resources --vm-name azure-playground-vm
az vm extension delete --resource-group azure-playground-resources --vm-name azure-playground-vm --name bootstrapper
az batch account create -g myresourcegroup -n mybatchaccount -l eastus
az storage account create -g myresourcegroup -n mystorageaccount -l eastus --sku Standard_LRS
az batch account set -g myresourcegroup -n mybatchaccount --storage-account mystorageaccount
We can now authenticate directly against the account for further CLI interaction.
az batch account login -g myresourcegroup -n mybatchaccount
az batch account show -g myresourcegroup -n mybatchaccount
az batch application create --resource-group myresourcegroup --name mybatchaccount --application-id myapp --display-name "My Application"
az batch application package create --resource-group myresourcegroup --name mybatchaccount --application-id myapp --package-file my-application-exe.zip --version 1.0
az batch application set --resource-group myresourcegroup --name mybatchaccount --application-id myapp --default-version 1.0
az batch pool node-agent-skus list
az batch pool create \
--id mypool-linux \
--vm-size Standard_A1 \
--image canonical:ubuntuserver:16.04.0-LTS \
--node-agent-sku-id “batch.node.ubuntu 16.04”
az batch pool resize --pool-id mypool-linux --target-dedicated 5
az batch pool show --pool-id mypool-linux
az batch node list --pool-id mypool-linux
If a particular node in the pool is having issues, it can be rebooted or reimaged. A typical node ID will be in the format 'tvm-xxxxxxxxxx_1-'.
az batch node reboot --pool-id mypool-linux --node-id tvm-123_1-20170316t000000z
az batch node delete \
--pool-id mypool-linux \
--node-list tvm-123_1-20170316t000000z tvm-123_2-20170316t000000z \
--node-deallocation-option requeue
az batch job create --id myjob --pool-id mypool
…where is your preferred shell for execution (/bin/sh, /bin/bash, /bin/ksh etc.), and /path/to/script.sh is, of course, the full path of the shell script you’re invoking to get things started.
az batch task create --job-id myjob --task-id task1 --application-package-references myapp#1.0 --command-line "/bin/<shell> -c /path/to/script.sh"
az batch task create --job-id myjob --json-file tasks.json
Now that all the tasks are added - we can update the job so that it will automatically be marked as completed once all the tasks are finished.
az batch job set --job-id myjob --on-all-tasks-complete terminateJob
az batch job show --job-id myjob
az batch task show --job-id myjob --task-id task1
az batch job delete --job-id myjob
If you HAVE AN SSH run this to create an Azure Container Service Cluster (~10 mins)
az acs create -n acs-cluster -g acsrg1 -d applink789
If you DO NOT HAVE AN SSH run this to create an Azure Container Service Cluster (~10 mins)
az acs create -n acs-cluster -g acsrg1 -d applink789 --generate-ssh-keys
az acs list --output table
az acs list -g acsrg1 --output table
az acs show -g acsrg1 -n acs-cluster --output list
az acs scale -g acsrg1 -n acs-cluster --new-agent-count 4
az acs delete -g acsrg1 -n acs-cluster
$ az config set core.output=table
Command group 'config' is experimental and under development. Reference and support levels: https://aka.ms/CLI_refstatus
$ az config set extension.use_dynamic_install=yes_prompt
Command group 'config' is experimental and under development. Reference and support levels: https://aka.ms/CLI_refstatus
$ az config set extension.run_after_dynamic_install=yes
Command group 'config' is experimental and under development. Reference and support levels: https://aka.ms/CLI_refstatus
https://learn.microsoft.com/en-us/cli/azure/azure-cli-configuration
# turn persisted parameters on
az config param-persist on
# Create a resource group which will store "resource group" and "location" in persisted parameter.
az group create --name RGlocalContext --location westeurope
# Create an Azure storage account omitting location and resource group.
az storage account create \
--name sa1localcontext \
--sku Standard_LRS
# Create a serverless function app in the resource group omitting storage account and resource group.
az functionapp create \
--name FAlocalContext \
--consumption-plan-location westeurope \
--functions-version 2
# See the stored parameter values
az config param-persist show```
<https://learn.microsoft.com/en-us/cli/azure/param-persist-howto>
## How to use Fiddler (web proxy) with the CLI?
```bash
export HTTP_PROXY="http://localhost:8888" HTTPS_PROXY="http://localhost:8888"
export AZURE_CLI_DISABLE_CONNECTION_VERIFICATION=1
az login
az account list
az account set -s <subscription>
az configure --defaults location=<location_name>
az configure --defaults group=<resourceGroupName>
Set an environment variable VAULT_NAME to your the name of your Key Vault resource,e.g.:
set VAULT_NAME=pvb-uat-euw-kv
Then run these commands:
del %VAULT_NAME%.csv
for /f %i in ('az keyvault secret list --vault-name %VAULT_NAME%') do @az keyvault secret show --vault-name %VAULT_NAME% --name %i -o tsv --query "{name:name, value:value}" >> %VAULT_NAME%.csv
more %VAULT_NAME%.csv
az webapp list [-g group] [-s sub]
set APP_NAME=pvb-live-euw-admin-as
az webapp config appsettings list -g pvb-live -n %APP_NAME% -o tsv > %APP_NAME%.settings.csv
az functionapp config appsettings list -g pvb-live -n pvb-live-euw-admin-as
set RG=pvb-uat
for /f %i in ('az webapp list -g %RG%' -o tsv --query "[].{name:name}"') do @az webapp config appsettings list -g %RG% -n %i -o tsv >> %RG%.%i.settings.csv
az account set -s Playground
RG=pvb-uat
az resource list -g $RG --query "[].{ name: name, kind: kind, type: type, location: location }" --output table
az account set -s Playground
RG=pvb-uat
az role assignment list --resource-group $RG --output json --query '[].{principalName:principalName, roleDefinitionName:roleDefinitionName, scope:scope}'
az account set -s Playground
RG=pvb-uat
# NB bash on Windows (WSL) may need the CR trimming:
# for scope in "$(az resource list -g $1 -o tsv --query '[].{ id: id }' | tr -d '\r')"; do
for scope in "$(az resource list -g $RG -o tsv --query '[].{ id: id }')"; do
echo IAM for $scope
az role assignment list --scope $scope -o table
done
for rg in $(az group list -o tsv --query "[].{name:name}" | tr -d '\r'); do
#echo resources in $rg
for scope in "$(az resource list -g $rg -o tsv --query '[].{ id: id }' | tr -d '\r')"; do
echo "$scope"
az role assignment list --scope "$scope" -o table
done
done
You can list all your Cosmos DBs in a subscription with something like this:
az cosmosdb list --subscription %subscriptionId% --query "[].{name:name, kind:kind, location:location, resourceGroup:resourceGroup}"
Given all your subscriptions IDs are:
az account list -o tsv --query "[].{id:id}"
Then all your "Cosmoses" can be queried like so:
for /f %s in ('az account list -o tsv --query "[].{id:id}"') do @az cosmosdb list --subscription %s --query "[].{name:name, kind:kind, location:location, resourceGroup:resourceGroup}" -o tsv
* In these examples, the type is "MongoDB". You could remove that ?kind=='MongoDB'
filter from the query and list all as above.
for /f %s in ('az account list -o tsv --query "[].{id:id}"') do @az cosmosdb list --subscription %s --query "[?kind=='MongoDB'].{name:name, kind:kind, location:location, resourceGroup:resourceGroup}" -o json
for sub in $(az account list -o tsv --query '[].{id:id}' | tr -d '\r'); do
az cosmosdb list --subscription $sub --query "[?kind=='MongoDB'].{name:name, kind:kind, location:location, resourceGroup:resourceGroup}" -o json
done
for sub in $(az account list -o tsv --query '[].{id:id}' | tr -d '\r'); do
for sql in $(az sql server list --subscription $sub --query "[].{name:name}" | tr -d '\r'); do
echo $sql
# az sql elastic-pool list --subscription $sub -o table
done
done
$ az webapp deployment source config-zip -g pvb-qat-rg -n pvb-qat-euw-myapp-as --src .\bin\Release\netcoreapp3.1\publish.zip
Getting scm site credentials for zip deployment
Starting zip deployment. This operation can take a while to complete ...
Deployment endpoint responded with status code 202
Active Author Author_email Complete Deployer End_time Is_readonly Is_temp Last_success_end_time Log_url Message Progress Received_time Site_name Start_time Status Status_text Url
-------- -------- -------------- ---------- ---------- ---------------------------- ------------- --------- ---------------------------- ---------------------------------------------------------------------------------- ----------------------------- ---------- -------------------------- ------------------------- ---------------------------- -------- ------------- ------------------------------------------------------------------------------
True N/A N/A True ZipDeploy 2021-01-30T11:53:11.3202611Z True False 2021-01-30T11:53:11.3202611Z https://pvb-qat-euw-myapp-as.scm.azurewebsites.net/api/deployments/latest/log Created via a push deployment 2021-01-30T11:53:09.85145Z pvb-qat-euw-myapp-as 2021-01-30T11:53:10.3827205Z 4 https://pvb-qat-euw-myapp-as.scm.azurewebsites.net/api/deployments/latest
$
az monitor metrics alert create -n "InfoCapchaSqlDtuOver80pct" -g "pvb-qat-rg" --scopes "dtu_used" --condition "avg Percentage DTU > 80" --description "Check to see if the Avg DTU exceeds 80%."
for group in "$(az group list -o tsv --query '[].{name:name}' | tr -d '\r')"; do
az monitor metrics alert list -g $group;
done
These notes assume that you already have an app service plan running a number of sites (web apps) that ALL want the same wildcard cert.
The problem being solved was how to point a number of sites to a company domain.
The aliases (e.g. alias trainer.foo-uk.com
onto CNAME pvb-live-eun-trainer-as.azurewebsites.net
) MUST already be configured in DNS -- Azure will check!
You might instead want to query a Resource Group. I chose a plan because I had another plan in the same resource group that I didn't want to configure. In this exmaple I want the LIVE sites running in EU North, i.e. pvb-live-eun-asp
.
$ az webapp list -g $resourceGroup --query "[?ends_with(appServicePlanId, '-eun-live-asp')].{name: name, plan: appServicePlanId}" -o table
Name Plan
----------------------- -------------------------------------------------------------------------------------------------
pvb-live-eun-trainer-as /subscriptions/.../resourceGroups/foo-live/providers/Microsoft.Web/serverfarms/ pvb-live-eun-asp
pvb-live-eun-manager-as /subscriptions/.../resourceGroups/foo-live/providers/Microsoft.Web/serverfarms/ pvb-live-eun-asp
pvb-live-eun-booking-as /subscriptions/.../resourceGroups/foo-live/providers/Microsoft.Web/serverfarms/ pvb-live-eun-asp
pvb-live-eun-admin-as /subscriptions/.../resourceGroups/foo-live/providers/Microsoft.Web/serverfarms/ pvb-live-eun-asp
pvb-live-eun-driver-as /subscriptions/.../resourceGroups/foo-live/providers/Microsoft.Web/serverfarms/ pvb-live-eun-asp
In a bash script create a mapping (an associative array) between the webapp name and the live subdomain
declare -A aliases=( \
[" pvb-live-eun-trainer-as"]="trainer" \
[" pvb-live-eun-manager-as"]="app-manager" \
[" pvb-live-eun-booking-as"]="booking" \
[" pvb-live-eun-admin-as"]="admin" \
[" pvb-live-eun-driver-as"]="app" \
)
pfxPassword=********
domain=pvb-uk.com
pfxPath=pvb-uk.pfx
resourceGroup=pvb-live
...
for webappname in $(az webapp list -g $resourceGroup --query "[?ends_with(appServicePlanId, 'eun-live-asp')].{name: name}" -o tsv); do
# Map the prepared custom domain name to the web app, lookiing up the mapping in dictionary (associative array) above
fqdn=${aliases[$webappname]}.$domain
echo Adding hostname $fqdn to $webappname...
az webapp config hostname add --webapp-name $webappname --resource-group $resourceGroup --hostname $fqdn
echo $fqdn added to $webappname.
# Upload the SSL certificate and get the thumbprint.
echo Uploading cert tp $webappname...
thumbprint=$(az webapp config ssl upload --certificate-file $pfxPath --certificate-password $pfxPassword --name $webappname --resource-group $resourceGroup --query thumbprint --output tsv)
echo Cert uploaded.
# Binds the uploaded SSL certificate to the web app.
echo Binding $thumbprint to $webappname...
# read -p "Press [Enter] key when ready ..."
az webapp config ssl bind --certificate-thumbprint $thumbprint --ssl-type SNI --name $webappname --resource-group $resourceGroup
echo "You can now browse to https://$fqdn"
read -p "Press [Enter] key to continue..."
done
if [ $? -ne 0 ]; then
echo "Failed to add hostname to $webappname"
# exit 1
fi
- https://github.com/Azure/azure-cli/blob/dev/doc/use_cli_effectively.md
- https://docs.microsoft.com/en-us/cli/azure/query-azure-cli?view=azure-cli-latest
- https://www.lytzen.name/2019/04/11/add-user-to-all-azure-subs.html
- https://docs.microsoft.com/en-us/cli/azure/webapp?view=azure-cli-latest#az-webapp-list
- Installation
- Virtual Machines
- VM-UTIL: List all virtual machines
- VM-UTIL: List all stopped virtual machines
- VM-UTIL: Check status of all virtual machines
- VM-UTIL: Get all ip addresses from stopped virtual machines
- VM-UTIL: List all snapshots in the date specified
- VM-SEC: List all snapshot in the date specified and without encryption
- VM-SEC: List SecurityGroups with SSH (22) open to Internet
- VM-SEC: List all server certificates
- Keys & Access Management
- Storage
- SQL
Ref: https://docs.microsoft.com/es-es/cli/azure/?view=azure-cli-latest
Function | Command |
---|---|
Install az on Windows |
Download MSI |
Install az on Mac |
brew install azure-cli |
Install az on Linux |
apt-get install azure-cli |
Configuring awscli | az login |
az vm list
az vm list -d \
--query "[?powerState=='VM deallocated'] || [?powerState=='VM stopped'] || [?powerState=='VM unknown']"
az vm list -d \
--query "[].[name, powerState]"
az vm list -d \
--query "[?powerState=='VM deallocated'].[name, powerState, publicIps] || [?powerState=='VM stopped'].[name, powerState, publicIps] || [?powerState=='VM unknown'].[name, powerState, publicIps]"
az snapshot list \
--query "[?timeCreated >= '2019-06-02']"
az snapshot list \
--query "[?timeCreated >= '2019-06-02'] && [?encryptionSettingsCollection==null]"
az network nsg list \
--query "[?securityRules[?access == 'Allow']].[name] && [?securityRules[?destinationPortRange == '22']].[name]"
az keyvault list \
--query "[].[vaultName] \
--out tsv"\
|xargs -I {} bash -c 'if [[ $(az keyvault certificate list --vault-name {}) ]]; then echo {} ; fi
az policy definition list
az group list
az ad group member list \
--group {name}
$Msolcred = Get-credential
Connect-MsolService -Credential $MsolCred
Get-MsolUser -All | where {$_.StrongAuthenticationMethods -ne $null} | Select-Object -Property UserPrincipalName, DisplayName
Get-MsolUser -All | where {$_.StrongAuthenticationMethods.Count -eq 0} | Select-Object -Property UserPrincipalName, DisplayName
az storage account list
az security alert list \
--query "[?contains(extendedProperties.resourceType, 'Storage')]"
az sql db tde show \
--server {name} \
--resource-group {name} \
--database {name}
Collection of commands I've found useful and don't want to forget or lose from my shell history.
# Set the context
az account set -s $subscriptionName
# Show context information
az account show
# Login with a service principal
az login --service-principal --username $clientId --password $clientSecret --tenant $tenantId
# Show a user
az ad user show --id $mail --query "displayName"
# Show a group
az ad group show -g $groupName --query "objectId"
# List group members
az ad group member list -g $groupName --query "[].displayName"
# List service principals
az ad sp list --display-name "Startswith..." --query "[].[displayName,objectId]"
# List projects
az devops project list --organization $orgUrl --query "value[].name" > projects
# List repositories
while read project; do az repos list --detect true --organization $orgUrl --project $project --query "[].{repoName: name,projectName: pr
oject.name}" >> repo_list; done < projects
az extension add --name $extensionName
# Set context
Set-AzContext -Subscription $SubscriptionName
# Get context
Get-AzContext
# Get role definition
$Role = Get-AzRoledefinition -Name $RoleName
# Modify permissions
$Role.Actions.Add("Microsoft.Compute/...")
$Role.Actions.Remove("Microsoft.Compute/...")
# Update role
Set-AzRoleDefinition -Role $Role
set VAULT_NAME=%1 | |
set SUB=%2 | |
:: NB Example commands to compare all **AppSettings** (as opposed to this cmd which is for KeyVault) : | |
:: | |
:: az webapp config appsettings list --name pvb-live-euw-myapp-as --subscription d45315f6-cafe-4537-93c2-f526f2d9755f -g | |
:: pvb-live-rg > pvb-live-euw-myapp-as.appsettings.txt | |
:: | |
:: az functionapp config appsettings list --name pvb-live-euw-myapp-fn --subscription df65c18f-cafe-4951-8a1a-d7a23a97d649 -g pvb-live-rg > pvb-live-euw-myapp-fn.appsettings.txt | |
:: | |
echo %VAULT_NAME% %SUB% > %VAULT_NAME%.txt | |
for /f %%i in ('az keyvault secret list --subscription %SUB% --vault-name %VAULT_NAME% -o tsv --query "[].{id:id}"') do @az keyvault secret show --id %%i -o tsv --query "{name:name, value:value}" >> %VAULT_NAME%.txt | |
echo written to %VAULT_NAME% |
@echo off | |
for /f %%i in ('az account list --query "[].id" -o tsv') do call :get_subs %%i | |
goto :eof | |
:get_subs | |
set sub=%1 | |
:: @echo sub: %sub% | |
for /f %%j in ('az group list --subscription %sub% --query "[].name" -o tsv') do call :get_service_plan %sub% %%j | |
goto :eof | |
:get_service_plan | |
set sub=%1 | |
set rg=%2 | |
::az appservice plan list -g %rg% --subscription %SUB% --query "[].{ Name: name, Sku: sku.name }" -o tsv | |
call az appservice plan list -g %rg% --subscription %SUB% --query "[].{ Name: name, Sku: sku.name }" -o tsv | |
goto :eof | |
:eof | |
echo Done. |
#!/bin/bash | |
# | |
# query-app-settings.sh | |
# | |
# List Appsettings in every slot of every webapp and function app for a given sub | |
# | |
# Optionally filter results that contain a given string. | |
# | |
# EXAMPLES: | |
# | |
# ./query-app-settings.sh NewOrbit | |
# | |
# - show all settings in the NewOrbit subscription | |
# | |
# ./query-app-settings.sh pvb Logging | |
# | |
# - show all "pvb" settings that contain the string "Logging" | |
# | |
# petevb@NOPVBP51:/mnt/c/Users/PetevanBlerk/code$ ./query-app-settings.sh | |
# RG APP SLOT NAME VALUE | |
# -------- ----------------------- ------- ------------------------------- ---------- | |
# pvb-live pvb-eun-live-booking-as staging Logging:Serilog:MinimumLevel Verbose | |
# pvb-uat pvb-eun-uat-booking-as staging Logging:Serilog:MinimumLevel Verbose | |
# pvb-uat pvb-eun-uat-admin-as Staging Logging:Serilog:MinimumLevel Verbose | |
# | |
# az group list --subscription foo --query [].name -o table | |
sub=${1:-foo} | |
# echo $sub | |
for rg in $(az group list --subscription $sub --query [].name -o tsv); do | |
# echo $rg. | |
for webapp in $(az webapp list --subscription $sub -g $rg --query [].name -o tsv); do | |
# echo $webapp.. | |
for slot in $(az webapp deployment slot list --subscription $sub -g $rg -n $webapp -o tsv --query "[].{ Name:name }"); do | |
# echo $slot... | |
az webapp config appsettings list --subscription $sub -g $rg -n $webapp --slot $slot --query "[?contains(name,'$2')].{ Group:'$rg', App:'$webapp', Slot:'$slot', Name:name, Value:value }" -o tsv | |
done | |
done | |
for fnapp in $(az functionapp list --subscription $sub -g $rg --query [].name -o tsv); do | |
# echo $fnapp.. | |
for slot in $(az functionapp deployment slot list --subscription $sub -g $rg -n $fnapp -o tsv --query "[].{ Name:name }"); do | |
# echo $slot... | |
az webapp config appsettings list --subscription $sub -g $rg -n $fnapp --slot $slot --query "[?contains(name,'$2')].{ Group:'$rg', App:'$fnapp', Slot:'$slot', Name:name, Value:value }" -o tsv | |
done | |
done | |
done |
#!/bin/bash | |
# | |
# query-cosmos-failover.sh | |
# | |
# List cosmos DBs in every resource group of a subscription and find their locations | |
# | |
sub=$1 | |
# az group list --subscription $1 --query [].name -o table | |
for resourceGroup in $(az group list --subscription $1 --query [].name -o tsv); do | |
# echo RESOURCE GROUP $resourceGroup\: | |
for database in $(az cosmosdb list --subscription $1 -g $resourceGroup --query [].name -o tsv); do | |
# echo Found '$database' Cosmos DB database. Querying ... | |
az cosmosdb list --subscription $1 -g $resourceGroup -o tsv --query "[].readLocations[].locationName | { Group:'$resourceGroup', Database:'$database', readLocations: join(', ', @), count: length(@) }" | |
done | |
done |
#!/bin/bash | |
# | |
# query-cosmos-throughput.sh | |
# | |
# List cosmos DBs in every resource group of a subscription and find their current thoughput, their max (ever) throughput, and whether they have per minute RU enabled. | |
# | |
# az group list --subscription pvb --query [].name -o table | |
for resourceGroup in $(az group list --subscription pvb --query [].name -o tsv); do | |
# echo RESOURCE GROUP $resourceGroup\: | |
for database in $(az cosmosdb list -g $resourceGroup --query [].name -o tsv); do | |
# echo Found '$database' Cosmos DB database. Querying ... | |
# az cosmosdb keys list -g $resourceGroup -n $database --type read-only-keys --query secondaryReadonlyMasterKey -o tsv | |
for collection in $(az cosmosdb collection list -d pvb -g $resourceGroup -n $database -o tsv --query [].id); do | |
az cosmosdb collection show -c $collection -d pvb -g $resourceGroup -n $database -o tsv \ | |
--query "{ Group:'$resourceGroup', Database:'$database', Collection:collection.id, CurrentThroughput:offer.content.offerThroughput, MaxEver:offer.content.offerMinimumThroughputParameters.maxThroughputEverProvisioned, IsRUPerMinuteEnabled: offerIsRUPerMinuteThroughputEnabled }" | |
done | |
done | |
done |
I think there's been a change in behaviour in WSL or the Azure CLI that had me puzzled for a bit.
When you run an az
command in bash on Windows you might get a CRLF (\r\n) in the response rather than just the LF (\n) you'd have on POSIX/linux environments.
I'm using Ubuntu 20.04 (Ubuntu 20.04.1 LTS) in WSL2 on Windows 10 (20H2 / 19042.746).
If you capture an az
command into a variable, e.g.:
local slotId=$(az $resourceType deployment slot list --name pvb-live-euw-mywebapp-as --resource-group pvb-live-rg -o tsv --query [].id) >/dev/null
echo "stop deployment slot with id $slotId"
az resource invoke-action --action stop --ids $slotId
and try to use it in a command you'll get an error, e.g.:
BadRequestError: Operation failed with status: 'Bad Request'. Details: 400 Client Error: Bad Request for url: https://management.azure.com/subscriptions/453dead-9ac1-cafe-2805-decafbad755f/resourceGroups/pvb- live-rg/providers/Microsoft.Web/sites/pvb-live-euw-mywebapp-as/slots/staging%0D/stop?api-version=2020-09-01
See the %0D
(CR) in that URL? (It's at the end just before the query string.) That's what's causing the HTTP 400. The reason it's there is because the slotId
I got back from the previous command has the CR of CRLF in it .
I'm not sure if that's a bug, but one solution is to pipe bash's transform, | tr -d '\r'
, to trim the trailing CR:
local slotId=$(az $resourceType deployment ... -o tsv --query [].id | tr -d '\r') >/dev/null
Note: This is not an issue with line endings in the script, but a problem with the line endings of the "response" to stdout.
Command az monitor metrics alert create : Create a metric-based alert rule.
Arguments --condition [Required] : The condition which triggers the rule. Usage: --condition {avg,min,max,total,count} [NAMESPACE.]METRIC {=,!=,>,>=,<,<=} THRESHOLD [where DIMENSION {includes,excludes} VALUE [or VALUE ...] [and DIMENSION {includes,excludes} VALUE [or VALUE ...] ...]]
Dimensions can be queried by adding the 'where' keyword and multiple dimensions can be
queried by combining them with the 'and' keyword.
Values for METRIC, DIMENSION and appropriate THRESHOLD values can be obtained from `az
monitor metrics list-definitions` command.
Due to server limitation, when an alert rule contains multiple criterias, the use of
dimensions is limited to one value per dimension within each criterion.
Multiple conditions can be specified by using more than one `--condition` argument.
--name -n [Required] : Name of the alert rule.
--resource-group -g [Required] : Name of resource group. You can configure the default group
using `az configure --defaults group=<name>`.
--scopes [Required] : Space-separated list of scopes the rule applies to. The
resources specified in this parameter must be of the same
type and exist in the same location.
--action -a : Add an action group and optional webhook properties to fire
when the alert is triggered.
Usage: --action ACTION_GROUP_NAME_OR_ID [KEY=VAL [KEY=VAL ...]]
Multiple action groups can be specified by using more than one `--action` argument.
--auto-mitigate : Automatically resolve the alert. Allowed values: false,
true.
--description : Free-text description of the rule.
--disabled : Create the rule in a disabled state. Allowed values: false,
true.
--evaluation-frequency : Frequency with which to evaluate the rule in "##h##m##s"
format. Default: 1m.
--region --target-resource-region : The region of the target resource(s) in scopes. This must be
provided when scopes is resource group or subscription.
--severity : Severity of the alert from 0 (critical) to 4 (verbose).
Default: 2.
--tags : Space-separated tags: key[=value] [key[=value] ...]. Use ""
to clear existing tags.
--target-resource-type --type : The resource type of the target resource(s) in scopes. This
must be provided when scopes is resource group or
subscription.
--window-size : Time over which to aggregate metrics in "##h##m##s" format.
Default: 5m.
Global Arguments --debug : Increase logging verbosity to show all debug logs. --help -h : Show this help message and exit. --only-show-errors : Only show errors, suppressing warnings. --output -o : Output format. Allowed values: json, jsonc, none, table, tsv, yaml, yamlc. Default: table. --query : JMESPath query string. See http://jmespath.org/ for more information and examples. --subscription : Name or ID of subscription. You can configure the default subscription using az account set -s NAME_OR_ID
. --verbose : Increase logging verbosity. Use --debug for full debug logs.
- Create a high CPU usage alert on a VM with no action.
az monitor metrics alert create -n alert1 -g {ResourceGroup} --scopes {VirtualMachineID} --condition "avg Percentage CPU > 90" --description "High CPU"
- Create a high CPU usage alert on a VM with email and webhook actions.
az monitor metrics alert create -n alert1 -g {ResourceGroup} --scopes {VirtualMachineID} \
--condition "avg Percentage CPU > 90" --window-size 5m --evaluation-frequency 1m \
--action "/subscriptions/<subscriptionId>/resourceGroups/<resourceGroupName>/providers/Microsoft.Insights/actionGroups/<actionGroupName>" apiKey={APIKey} type=HighCPU \
--description "High CPU"
- Create an alert when a storage account shows a high number of slow transactions, using multi-dimensional filters.
az monitor metrics alert create -g {ResourceGroup} -n alert1 --scopes {StorageAccountId} \
--description "Storage Slow Transactions" \
--condition "total transactions > 5 where ResponseType includes Success" \
--condition "avg SuccessE2ELatency > 250 where ApiName includes GetBlob"
- Create a metric-based alert rule that monitors a custom metric.
az monitor metrics alert create -n "metric alert rule on a custom metric" -g "Demos"
--scopes {VirtualMachineID} \
--condition "max Azure.VM.Windows.GuestMetrics.Memory\Available Bytes > 90" \
--window-size 5m --evaluation-frequency 1m
- Create a high CPU usage alert on several VMs with no actions.
az monitor metrics alert create -n alert1 -g {ResourceGroup} --scopes {VirtualMachineID1}
{VirtualMachineID2} {VirtualMachineID3} \
--condition "avg Percentage CPU > 90" --description "High CPU"
For more specific examples, use: az find "az monitor metrics alert create"
Please let us know how we are doing: https://aka.ms/azureclihats
Reference
I’m a DevOps/SRE/DevSecOps/Cloud Expert passionate about sharing knowledge and experiences. I am working at Cotocus. I blog tech insights at DevOps School, travel stories at Holiday Landmark, stock market tips at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at I reviewed , and SEO strategies at Wizbrand.
Please find my social handles as below;
Rajesh Kumar Personal Website
Rajesh Kumar at YOUTUBE
Rajesh Kumar at INSTAGRAM
Rajesh Kumar at X
Rajesh Kumar at FACEBOOK
Rajesh Kumar at LINKEDIN
Rajesh Kumar at PINTEREST
Rajesh Kumar at QUORA
Rajesh Kumar at WIZBRAND
Very informative blog, thanks for sharing it.