概要
Azureで動いているIaaSの仮想マシンの停止等を いちいち Azure Portal に入らずに、サクッと Azure CLI で実行するための手順となります。
ローカル環境
- macOS Monterey 12.1
- python 3.8.3
- Azure CLI 2.28.0
前提条件
- Azure環境がすでに用意されていること(テナント/サブスクリプション)
- ローカル環境に「azure cli」がインストールされていること
Azure CLI からの 仮想マシン
リソースグループ内にある仮想マシンの一覧の取得
$ az vm list -g <Resource_Group_Name> -d --output table
Name ResourceGroup PowerState PublicIps Fqdns Location Zones
--------------- --------------- ------------ ------------ ------- ---------- -------
vm-ituru-ubuntu rg_ituru_vm02 VM running 20.188.24.42 japaneast
仮想マシンのIPアドレスの確認
$ az vm list-ip-addresses --resource-group <Resource_Group_Name> --name <vm-name> --output table
VirtualMachine PublicIPAddresses PrivateIPAddresses
---------------- ------------------- --------------------
vm-ituru-ubuntu 20.188.24.42 10.0.1.4
仮想マシン・インスタンスの確認
$ az vm get-instance-view --resource-group <Resource_Group_Name> --name <vm-name> --query instanceView.statuses --output table
Code Level DisplayStatus Time
--------------------------- ------- ---------------------- --------------------------------
ProvisioningState/succeeded Info Provisioning succeeded 2022-01-24T12:18:02.460457+00:00
PowerState/running Info VM running
仮想マシンの停止
$ az vm stop --resource-group <Resource_Group_Name> --name <vm-name>
About to power off the specified VM...
It will continue to be billed. To deallocate a VM, run: az vm deallocate.
このままだと、課金されたままなので、メッセージ通りのコマンドを実行
$ az vm deallocate --resource-group <Resource_Group_Name> --name <vm-name>
いちおう、仮想マシンのステータスを確認
$ az vm list -g <Resource_Group_Name> -d --output table
Name ResourceGroup PowerState PublicIps Fqdns Location Zones
--------------- --------------- -------------- ----------- ------- ---------- -------
vm-ituru-ubuntu rg_ituru_vm02 VM deallocated japaneast
仮想マシンの起動
$ az vm start --resource-group <Resource_Group_Name> --name <vm-name>
再度、仮想マシンのステータスを確認(グローバルIPアドレスが変わってます)
$ az vm list -g <Resource_Group_Name> -d --output table
Name ResourceGroup PowerState PublicIps Fqdns Location Zones
--------------- --------------- ------------ -------------- ------- ---------- -------
vm-ituru-ubuntu rg_ituru_vm02 VM running 20.210.209.139 japaneast
まとめ
これで、Azure CLI でサクッと 仮想マシンの停止・起動ができるようになりました。