安装

官方文档:
https://docs.microsoft.com/zh-cn/cli/azure/install-azure-cli

除了图形化安装,还可以通过 PowerShell 用命令行安装,注意使用管理员运行 Powershell

  1. Invoke-WebRequest -Uri https://aka.ms/installazurecliwindows -OutFile .\AzureCLI.msi
  2. Start-Process msiexec.exe -Wait -ArgumentList '/I AzureCLI.msi /quiet'
  3. Remove-Item .\AzureCLI.msi

重新打开一个 PowerShell 就可以使用 az 命令了

  1. # 检查版本
  2. az version
  3. # 升级 cli
  4. az upgrade

登录和配置

  1. # 打开默认的浏览器进行登录
  2. az login
  3. # 使用用户名和密码登录,注意:不支持启用了两步认证的账户
  4. az login -u johndoe@contoso.com -p VerySecret

默认输出的返回格式是 json ,可以配置 az cli 使用 table

  1. az configure

订阅管理

Azure 的订阅 (Subscription) 类似于 AWS 的账户 (aws account),在 az cli 中,如果不加指定订阅的参数,就是对默认的订阅里的云资源(vm,disk,network)进行操作

查看订阅

  1. # 只查看 enabled 订阅
  2. az account list
  3. # 查看包括 disabled 订阅
  4. az account list --all
  5. # 查看订阅的 TenantID
  6. az account show --subscription <Name|ID> --output json

切换订阅

  1. az account set --subscription <Name|ID>

查看VM

  1. az vm list
  2. # 查询有 VM 的 ResourceGroup
  3. az vm list --query [].resourceGroup -o tsv | Sort-Object -Unique
  4. # 查询某个订阅下,Overview 重点关注的 VM 信息
  5. az vm list --show-detail --query "[].{Location:location, Zone:zones[0], ResourceGroup:resourceGroup, Name:name, VMID:vmId, VMSize:hardwareProfile.vmSize, OS:storageProfile.osDisk.osType, ComputerName:osProfile.computerName, AdminUser:osProfile.adminUsername, State:powerState, PrivateIps:privateIps}" -o table
  6. # 增加筛选条件
  7. az vm list --show-detail --query "[?storageProfile.osDisk.osType=='Linux'].{Location:location, Zone:zones[0], ResourceGroup:resourceGroup, Name:name, VMID:vmId, VMSize:hardwareProfile.vmSize, OS:storageProfile.osDisk.osType, ComputerName:osProfile.computerName, AdminUser:osProfile.adminUsername, State:powerState, PrivateIps:privateIps}" -o table
  8. # 查询某个 VM 完整的详细信息,并用返回 json 格式
  9. az vm show --resource-group <> --name <> --show-detail -o jsonc
  10. # 查询某个 VM 某个属性的具体值, tsv 的 output 表示去掉 Result 表头(Result)及表头虚线(-------)
  11. az vm show --resource-group <> --name <> --show-detail --query powerState -o tsv
  12. # 查询某个 VM 多个属性的具体值
  13. az vm show --resource-group <> --name <> --show-detail --query '[osProfile.adminUsername, osProfile.linuxConfiguration.ssh.publicKeys[0].keyData]' -o tsv