LoginSignup
2
1

More than 5 years have passed since last update.

貼って使う Azure CLI スニペット(Virtual Machine編)

Last updated at Posted at 2019-02-12

概要

  • Azure リソースのメンテナンス等で使えそうなコマンドのスニペット(PowerShell ベース)をまとめました
  • PowerShell コンソールに貼って使えます
  • 今回は Virtual Machine に関するスニペットをまとめます

前提

  • Azure CLI がインストールされている前提です
  • 実行するには、事前に az login コマンドで 認証する必要があります(参考:Azure CLI の概要 - サインイン
  • 環境情報:
    • Azure CLI(v.2.0.57)
    • PowerShell(v.5.1.17134.407)
  • 安全に試せるよう 情報取得系 中心にまとめます(一部注意事項あります)
  • 一部のスニペットは実行時にパラメータが必要となります

VM の一覧を取得したい

az vm list

VM名 だけ一覧取得したい

(az vm list | ConvertFrom-Json) | % {$_.name}

Windows VM だけ、名称・リソースグループ を一覧表示したい

(az vm list | ConvertFrom-Json) | where {$_.storageProfile.osDisk.osType -eq "Windows"} | % {$_.name + " (" + $_.resourceGroup + ")"}

Linux VM だけ、名称・リソースグループ を一覧取得したい

(az vm list | ConvertFrom-Json) | where {$_.storageProfile.osDisk.osType -eq "Linux"} | % {$_.name + " (" + $_.resourceGroup + ")"}

全VM の状態を一覧取得したい

  • 【注意】1件1件 VMの状態を取得するため時間がかかります
$st = @{
    "VM starting" = "開始中";
    "VM running" = "実行中";
    "VM stopping" = "停止中";
    "VM stopped" = "停止済み";
    "VM deallocating" = "割り当て解除中";
    "VM deallocated" = "割り当て解除済み";
}; `
(az vm list | ConvertFrom-Json) | `
    % { (az vm get-instance-view -g $_.resourceGroup -n $_.name | ConvertFrom-Json) | `
        % { $_.name + " (" + $_.resourceGroup + ") `n" + `
        "  状態:" + $st[$_.instanceView.statuses[1].displayStatus]  + "`n" + `
        "  OS:" + $_.storageProfile.osDisk.osType }};

追加のデータディスク容量(があれば)を一覧取得したい

(az vm list | ConvertFrom-Json) | `
    % {$_.name + " (" + $_.resourceGroup + ") `n" + `
    (($_.storageProfile.dataDisks) | % {"  データディスク: " + $_.diskSizeGb + " GB`n  "} )}
  • データディスクがない:VM名の下になにも表示されない
  • データディスクが複数ある:その分だけディスクサイズが表示される

全VMのIPを一覧取得したい

az vm list-ip-addresses --output table

特定のIPがどのVMで使用されているか確認したい

Param(
    [Parameter(Mandatory=$true)] $ipAddress
); `
(az vm list-ip-addresses | ConvertFrom-Json) | `
    % {
        if ($_.virtualMachine.network.privateIpAddresses -contains $ipAddress) { $_.virtualMachine.name + " (" + $_.virtualMachine.resourceGroup + ") で使用中" };
        if ($_.virtualMachine.network.publicIpAddresses -contains $ipAddress) { $_.virtualMachine.name + " (" + $_.virtualMachine.resourceGroup + ") で使用中" };
    }
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1