🚀 DevOps & SRE Certification Program 📅 Starting: 1st of Every Month 🤝 +91 8409492687 🔍 Contact@DevOpsSchool.com

Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours on Instagram and YouTube and waste money on coffee and fast food, but won’t spend 30 minutes a day learning skills to boost our careers.
Master in DevOps, SRE, DevSecOps & MLOps!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

Azure CLI Tutorials: Installations and User Guide

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

QuestionAnswer
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 interactiveaz scenarioaz next, and az find.

Learning Azure CLI

There are several reference commands that provide interactive prompts to help you learn the Azure CLI.

CommandDescriptionExample
az interactiveIn 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 scenarioGet 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 nextGet 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 findThis is an AI robot that will return reference examples for keywords.Type az find "active subscription" in your console then Enter.

Common usage questions

QuestionReference 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 createCreate a new resource group.
az group deleteDelete a resource group.
az group deploymentManage Azure Resource Manager deployments.
az group deployment cancelCancels a currently running template deployment.
az group deployment createStart a deployment.
az group deployment deleteDeletes a deployment from the deployment history.
az group deployment exportExport the template used for deployment.
az group deployment listGet all the deployments for a resource group.
az group deployment operationManage deployment operations.
az group deployment operation listGets all deployments operations for deployment.
az group deployment operation showGet a deployment’s operation.
az group deployment showGets a deployment.
az group existsCheck if a resource group exists.
az group listList resource groups.
az group lockManage Azure resource group locks.
az group lock createCreate a resource group lock.
az group lock deleteDelete a resource group lock.
az group showGets a resource group.
az group updateUpdate a resource group.

2) Manage Linux or Windows virtual machines.

COMMANDS
az vm applicationManage applications for VM.
az vm application listList applications for VM.
az vm application setSet appliations for VM.
az vm assess-patchesAssess patches on a VM.
az vm auto-shutdownManage auto-shutdown for VM.
az vm availability-setGroup resources into availability sets.
az vm availability-set createCreate an Azure Availability Set.
az vm availability-set deleteDelete an availability set.
az vm availability-set listList availability sets.
az vm availability-set list-sizesList VM sizes for an availability set.
az vm availability-set showGet information for an availability set.
az vm availability-set updateUpdate an Azure Availability Set.
az vm captureCapture information for a stopped VM.
az vm convertConvert a VM with unmanaged disks to use managed disks.
az vm createCreate an Azure Virtual Machine.
az vm deallocateDeallocate a VM.
az vm deleteDelete a VM.
az vm diagnosticsConfigure the Azure Virtual Machine diagnostics extension.
az vm diskManage the managed data disks attached to a VM.
az vm disk attachAttach a managed persistent disk to a VM. Please note that –ids only supports one disk.
az vm disk detachDetach a managed disk from a VM.
az vm encryptionManage encryption of VM disks.
az vm encryption showShow encryption status.
az vm extensionManage extensions on VMs.
az vm extension image list-versionsList the versions for available extensions.
az vm get-instance-viewGet instance information about a VM.
az vm hostManage Dedicated Hosts for Virtual Machines.
az vm host createCreate a dedicated host.
az vm host deleteDelete a dedicated host.
az vm identityManage service identities of a VM.
az vm identity assignEnable managed service identity on a VM.
az vm identity removeRemove managed service identities from a VM.
az vm identity showDisplay VM’s managed identity info.
az vm image list-skusList the VM image SKUs available in the Azure Marketplace.
az vm listList details of Virtual Machines.
az vm list-ip-addressesList IP addresses associated with a VM.
az vm list-sizesList available sizes for VMs.
az vm list-skusGet details for compute-related resource SKUs.
az vm list-usageList available usage resources for VMs.
az vm list-vm-resize-optionsList available resizing options for VMs.
az vm monitorManage monitor aspect for a vm.
az vm nicManage network interfaces. See also az network nic.
az vm nic addAdd existing NICs to a VM.
az vm nic listList the NICs available on a VM.
az vm open-portOpens a VM to inbound traffic on specified ports.
az vm redeployRedeploy an existing VM.
az vm repairAuto repair commands to fix VMs.
az vm resizeUpdate a VM’s size.
az vm restartRestart VMs.
az vm secretManage VM secrets.
az vm secret addAdd a secret to a VM.
az vm secret formatTransform secrets into a form that can be used by VMs and VMSSes.
az vm secret listList secrets on a VM.
az vm secret removeRemove a secret from a VM.
az vm startStart a stopped VM.
az vm stopPower off (stop) a running VM.
az vm updateUpdate the properties of a VM.
az vm userManage user accounts for a VM.
az vm user deleteDelete a user account from a VM.
az vm user reset-sshReset the SSH configuration on a VM.
az vm user updateUpdate a user account.
az vm waitPlace the CLI in a waiting state until a condition of the VM is met.

3) Manage storage accounts.

COMMANDS
az storage account check-nameCheck that the storage account name is valid and is not already in use.
az storage account createCreate a storage account.
az storage account deleteDelete a storage account.
az storage account encryption-scopeManage encryption scope for a storage account.
az storage account failoverFailover request can be triggered for a storage account in case of availability issues.
az storage account file-service-propertiesManage the properties of file service in storage account.
az storage account generate-sasGenerate a shared access signature for the storage account.
az storage account keysManage storage account keys.
az storage account listList storage accounts.
az storage account management-policyManage storage account management policies.
az storage account network-ruleManage network rules.
az storage account or-policyManage storage account Object Replication Policy.
az storage account or-policy createCreate Object Replication Service Policy for storage account.
az storage account or-policy deleteDelete specified Object Replication Service Policy associated with the specified storage account.
az storage account private-endpoint-connectionManage storage account private endpoint connection.
az storage account private-link-resourceManage storage account private link resources.
az storage account private-link-resource listGet the private link resources that need to be created for a storage account.
az storage account revoke-delegation-keysRevoke all user delegation keys for a storage account.
az storage account showShow storage account properties.
az storage account show-connection-stringGet the connection string for a storage account.

4) Manage KeyVault keys, secrets, and certificates.

COMMANDS
az keyvault backupManage full HSM backup.
az keyvault certificateManage certificates.
az keyvault certificate createCreate a Key Vault certificate.
az keyvault createCreate a Vault or HSM.
az keyvault deleteDelete a Vault or HSM.
az keyvault delete-policyDelete security policy settings for a Key Vault.
az keyvault keyManage keys.
az keyvault key backupRequest that a backup of the specified key be downloaded to the client.
az keyvault key createCreate a new key, stores it, then returns key parameters and attributes to the client.
az keyvault key decryptDecrypt a single block of encrypted data.
az keyvault key deleteDelete a key of any type from storage in Vault or HSM.
az keyvault key downloadDownload the public part of a stored key.
az keyvault key encryptEncrypt an arbitrary sequence of bytes using an encryption key that is stored in a Vault or HSM.
az keyvault key restoreRestore a backed up key to a Vault or HSM.
az keyvault key rotateRotate the key based on the key policy by generating a new version of the key.
az keyvault key rotation-policyManage key’s rotation policy.
az keyvault key showGet a key’s attributes and, if it’s an asymmetric key, its public material.
az keyvault key show-deletedGet the public part of a deleted key.
az keyvault listList Vaults and/or HSMs.
az keyvault list-deletedGet information about the deleted Vaults or HSMs in a subscription.
az keyvault network-ruleManage vault network ACLs.
az keyvault recoverRecover a Vault or HSM.
az keyvault restoreManage full HSM restore.
az keyvault restore startRestore a full backup of a HSM.
az keyvault roleManage user roles for access control.
az keyvault secretManage secrets.
az keyvault secret backupBacks up the specified secret.
az keyvault secret listList secrets in a specified key vault.
az keyvault secret showGet a specified secret from a given key vault.
az keyvault storageManage storage accounts.
az keyvault updateUpdate the properties of a Vault.

5) Manage SQL servers.

COMMANDS
az sql server createCreate a server.
az sql server deleteDeletes a server.
az sql server dns-aliasManage a server’s DNS aliases.
az sql server firewall-ruleManage a server’s firewall rules.
az sql server firewall-rule createCreate a firewall rule.
az sql server keyManage a server’s keys.
az sql server key createCreates a server key.
az sql server key showShows a server key.
az sql server listList available servers.
az sql server list-usagesReturns server usages.
az sql server outbound-firewall-ruleManage a server’s outbound firewall rules.
az sql server showGets a server.
az sql server vnet-ruleManage a server’s virtual network rules.
az sql server vnet-rule createCreate a virtual network rule to allows access to an Azure SQL server.
az sql server vnet-rule deleteDeletes the virtual network rule with the given name.
az sql server vnet-rule listGets a list of virtual network rules in a server.

Azure CLI 2.0 Cheatsheet

Azure CLI 2.0 cheatsheet for Login, Resources, VMs, Resource groups, Storage, Batch, and Containers.

Logging in

Login with web

az login

Login in CLI

az login -u myemail@address.com

List accounts

az account list

Set subscription

az account set --subscription "xxx"

Listing locations and resources / general

List all locations

az account list-locations

List all my resource groups

az resource list

Get what version of the CLI you have

azure --version

Get help

azure help

Creating a basic VM / Resource Group / Storage Account

Get all available VM sizes

az vm list-sizes --location eastus

Get all available VM images for Windows and Linux

az vm image list --output table

Create a Linux VM

az vm create --resource-group myResourceGroup --name myVM --image ubuntults

Create a Windows VM

az vm create --resource-group myResourceGroup --name myVM --image win2016datacenter

Create a Resource group

az group create --name myresourcegroup --location eastus

Create a Storage account.

az storage account create -g myresourcegroup -n mystorageaccount -l eastus --sku Standard_LRS

DELETING A RESOURCE GROUP

Permanetly deletes a resource group

az group delete --name myResourceGroup

Managing VM's

List your VMs

az vm list

Start a VM

az vm start --resource-group myResourceGroup --name myVM

Stop a VM

az vm stop --resource-group myResourceGroup --name myVM

Deallocate a VM

az vm deallocate --resource-group myResourceGroup --name myVM

Restart a VM

az vm restart --resource-group myResourceGroup --name myVM

Redeploy a VM

az vm redeploy --resource-group myResourceGroup --name myVM

Delete a VM

az vm delete --resource-group myResourceGroup --name myVM

Create image of a VM

az image create --resource-group myResourceGroup --source myVM --name myImage

Create VM from image

az vm create --resource-group myResourceGroup --name myNewVM --image myImage

List VM extensions

az vm extension list --resource-group azure-playground-resources --vm-name azure-playground-vm

Delete VM extensions

az vm extension delete --resource-group azure-playground-resources --vm-name azure-playground-vm --name bootstrapper

Managing Batch Account

Create a Batch account.

az batch account create -g myresourcegroup -n mybatchaccount -l eastus

Create a Storage account.

az storage account create -g myresourcegroup -n mystorageaccount -l eastus --sku Standard_LRS

Associate Batch with storage account.

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

Display the details of our created account.

az batch account show -g myresourcegroup -n mybatchaccount

Create a new application.

az batch application create --resource-group myresourcegroup --name mybatchaccount --application-id myapp --display-name "My Application"

Add zip files to application

az batch application package create --resource-group myresourcegroup --name mybatchaccount --application-id myapp --package-file my-application-exe.zip --version 1.0

Assign the application package as the default version.

az batch application set --resource-group myresourcegroup --name mybatchaccount --application-id myapp --default-version 1.0

Retrieve a list of available images and node agent SKUs.

az batch pool node-agent-skus list

Create new Linux pool with VM config

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”

Now let's resize the pool to start up some VMs.

az batch pool resize --pool-id mypool-linux --target-dedicated 5

We can check the status of the pool to see when it has finished resizing.

az batch pool show --pool-id mypool-linux

List the compute nodes running in a pool.

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

Re-allocate work to another node.

az batch node delete \
    --pool-id mypool-linux \
    --node-list tvm-123_1-20170316t000000z tvm-123_2-20170316t000000z \
    --node-deallocation-option requeue

Create a new job to encapsulate the tasks that we want to add.

az batch job create --id myjob --pool-id mypool

Add tasks to the job.

…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"

Add many tasks at once

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

Monitor the status of the job.

az batch job show --job-id myjob

Monitor the status of a task.

az batch task show --job-id myjob --task-id task1

Delete a job

az batch job delete --job-id myjob

Managing Containers

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

List clusters under your whole subscription

az acs list --output table

List clusters in a resource group

az acs list -g acsrg1 --output table

Display details of a container service cluster

az acs show -g acsrg1 -n acs-cluster --output list

Scale using ACS

az acs scale -g acsrg1 -n acs-cluster --new-agent-count 4

Delete a cluster

az acs delete -g acsrg1 -n acs-cluster

az CLI cheatsheet / FAQ

set defaults

$ 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

Persistent parameters

# 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

How to set your environment and defaults?

az login
az account list
az account set -s <subscription>

az configure --defaults location=<location_name>
az configure --defaults group=<resourceGroupName>

List all the secrets in KeyVault?

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

List app services?

az webapp list [-g group] [-s sub]

View app settings?

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

Backup all app settings?

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

List resources in a group?

az account set -s Playground
RG=pvb-uat

az resource list -g $RG --query "[].{ name: name, kind: kind, type: type, location: location }" --output table

IAM

IAM for a RG?

az account set -s Playground
RG=pvb-uat

az role assignment list --resource-group $RG --output json --query '[].{principalName:principalName, roleDefinitionName:roleDefinitionName, scope:scope}'

IAM for resources in a RG?

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

IAM for groups in subscription?

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

List all your types of cosmos db?

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

Find a particular type* of Cosmos DB?

* In these examples, the type is "MongoDB". You could remove that ?kind=='MongoDB' filter from the query and list all as above.

Windows

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

bash

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

Find Elastic Pools?

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

Deploy local website (or other) ?

$ 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

$

Create alerts?

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%."

List alerts?

for group in "$(az group list -o tsv --query '[].{name:name}' | tr -d '\r')"; do
  az monitor metrics alert list -g $group;
done

Using Azure CLI to add cert and hostname to web apps

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!

First, how to get the interesting App Service Plan

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" \
)

Next loop around those Web Apps

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

Consider adding error handling and whether you want to exit or continue

if [ $? -ne 0 ]; then
    echo "Failed to add hostname to $webappname"
    # exit 1
fi

Further Reading

AZURE-CLI Cheatsheet

Table of content


Installation

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

Virtual Machines

VM-UTIL: List all virtual machines

az vm list

VM-UTIL: List all stopped virtual machines

az vm list -d \
    --query "[?powerState=='VM deallocated'] || [?powerState=='VM stopped'] || [?powerState=='VM unknown']"

VM-UTIL: Check status of all virtual machines

az vm list -d \
    --query "[].[name, powerState]"

VM-UTIL: Get all ip addresses from stopped virtual machines

az vm list -d \
    --query "[?powerState=='VM deallocated'].[name, powerState, publicIps] || [?powerState=='VM stopped'].[name, powerState, publicIps] || [?powerState=='VM unknown'].[name, powerState, publicIps]"

VM-UTIL: List all snapshots in the date specified

az snapshot list \
    --query "[?timeCreated >= '2019-06-02']"

VM-SEC: List all snapshot in the date specified and without encryption

az snapshot list \
    --query "[?timeCreated >= '2019-06-02'] && [?encryptionSettingsCollection==null]"

VM-SEC: List SecurityGroups with SSH (22) open to Internet

az network nsg list \
    --query "[?securityRules[?access == 'Allow']].[name] && [?securityRules[?destinationPortRange == '22']].[name]"

VM-SEC: List all server certificates

az keyvault list \
    --query "[].[vaultName] \
    --out tsv"\
    |xargs -I {} bash -c 'if [[ $(az keyvault certificate list --vault-name {}) ]]; then echo {} ; fi

Keys & Access Management

KAM-UTIL: List all policies

az policy definition list

KAM-UTIL: List all groups

az group list

KAM-UTIL: Get users for a specified for a given group

az ad group member list \
    --group {name}

KAM-SEC: Check if user has MFA enabled

$Msolcred = Get-credential
Connect-MsolService -Credential $MsolCred
Get-MsolUser -All | where {$_.StrongAuthenticationMethods -ne $null} | Select-Object -Property UserPrincipalName, DisplayName

KAM-SEC: Check users with no MFA enabled

Get-MsolUser -All | where {$_.StrongAuthenticationMethods.Count -eq 0} | Select-Object -Property UserPrincipalName, DisplayName

Storage

STR-UTIL: List all storages

az storage account list

STR-UTIL: Check alerts for storage accounts

az security alert list \
    --query "[?contains(extendedProperties.resourceType, 'Storage')]"

SQL

SQL-SEC: Check if a database has transparent data encryption enabled

az sql db tde show \
    --server {name} \
    --resource-group {name} \
    --database {name}

Az CLI

Collection of commands I've found useful and don't want to forget or lose from my shell history.

Account

# 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

Active Directory

# 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]"

DevOps

# 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

Extensions

az extension add --name $extensionName

Azure PowerShell

Account

# Set context
Set-AzContext -Subscription $SubscriptionName
# Get context
Get-AzContext

Custom RBAC roles

# 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
view raw README.md hosted with ❤ by GitHub
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

Trim trailing %0D from az CLI's reponse

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.

Examples

  • 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

Subscribe
Notify of
guest


1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Ravi
Ravi
1 year ago

Very informative blog, thanks for sharing it.

Certification Courses

DevOpsSchool has introduced a series of professional certification courses designed to enhance your skills and expertise in cutting-edge technologies and methodologies. Whether you are aiming to excel in development, security, or operations, these certifications provide a comprehensive learning experience. Explore the following programs:

DevOps Certification, SRE Certification, and DevSecOps Certification by DevOpsSchool

Explore our DevOps Certification, SRE Certification, and DevSecOps Certification programs at DevOpsSchool. Gain the expertise needed to excel in your career with hands-on training and globally recognized certifications.

1
0
Would love your thoughts, please comment.x
()
x