Microsoft Azureはaz vm run-commandコマンドを使用すると、SSHログインやRDP接続をせずにコマンドを実行する事ができます。SSHやRDPのポートをオープンしない事でセキュリティリスクを低減する目的で使ったり、ちょっとしたジョブを組む目的で使うと非常に便利な仕組みです。
このページでは、「アクション実行コマンド(az vm run-command invoke)」と「マネージド実行コマンド(az vm run-command create)」を説明します。
前提
公式ドキュメント
参考になる公式ドキュメントを以下に示します。
事前設定
以下、リソースグループを作成します。
az group create --name MyResourceGroup --location japaneast
動作確認用の仮想マシンを作成します。
az vm create \ --resource-group MyResourceGroup \ --name linux010 \ --image procomputers:rocky-linux-8-minimal:rocky-linux-8-minimal:latest \ --size Standard_B1s \ --admin-username azureuser \ --ssh-key-values ~/.ssh/authorized_keys
アクション実行コマンド
コマンドの実行例
コマンドを実行する例は以下の通りです。以下のように操作すればSSHログインする事なくSELinuxが有効かどうかを調べる事ができます。
az vm run-command invoke \ --resource-group MyResourceGroup \ --name linux010 \ --command-id RunShellScript \ --scripts 'getenforce'
実行結果は以下の通りです。コマンド実行時の標準出力もエラー出力も表示されます。
$ az vm run-command invoke \
--resource-group MyResourceGroup \
--name linux010 \
--command-id RunShellScript \
--scripts 'getenforce'
{
"value": [
{
"code": "ProvisioningState/succeeded",
"displayStatus": "Provisioning succeeded",
"level": "Info",
"message": "Enable succeeded: \n[stdout]\nPermissive\n\n[stderr]\n",
"time": null
}
]
}
ファイルを指定した実行
コマンドを1行1行指定するのではなく、予めファイルにコマンドを羅列しておき、それを実行する事もできます。例えば、nginxのインストールと付随作業を同時に実行する操作例は以下の通りです。
cat << EOF > install_nginx.sh setenforce 0 dnf install -y nginx systemctl enable nginx.service --now systemctl disable firewalld.service --now EOF az vm run-command invoke \ --resource-group MyResourceGroup \ --name linux010 \ --command-id RunShellScript \ --scripts @install_nginx.sh
デバッグや実行履歴など
スクリプトの実行履歴は/var/lib/waagent/run-command/download/配下に記録されています。
[root@linux010 ~]# dnf install -y tree
<omitted>
[root@linux010 ~]# tree /var/lib/waagent/run-command/download/
/var/lib/waagent/run-command/download/
├── 0
│ ├── script.sh
│ ├── stderr
│ └── stdout
└── 1
├── script.sh
├── stderr
└── stdout
2 directories, 6 files
実際に実行されたコマンドや標準出力やエラー出力が記録されています。
[root@linux010 ~]# cat /var/lib/waagent/run-command/download/1/script.sh setenforce 0 dnf install -y nginx systemctl enable nginx.service --now systemctl disable firewalld.service --now [root@linux010 ~]# [root@linux010 ~]# [root@linux010 ~]# cat /var/lib/waagent/run-command/download/1/stdout OpenLogic packages for x86_64 67 kB/s | 9.7 kB 00:00 Rocky Linux 8 - AppStream 4.0 MB/s | 9.7 MB 00:02 Rocky Linux 8 - BaseOS 2.4 MB/s | 6.7 MB 00:02 Rocky Linux 8 - Extras 8.5 kB/s | 12 kB 00:01 Rocky Linux 8 - PowerTools 834 kB/s | 2.6 MB 00:03 <omitted> nginx-mod-http-perl-1:1.14.1-9.0.1.module+el8.0.0+5347+9282027e.x86_64 nginx-mod-http-xslt-filter-1:1.14.1-9.0.1.module+el8.0.0+5347+9282027e.x86_64 nginx-mod-mail-1:1.14.1-9.0.1.module+el8.0.0+5347+9282027e.x86_64 nginx-mod-stream-1:1.14.1-9.0.1.module+el8.0.0+5347+9282027e.x86_64 Complete!
コマンド一覧
今までの操作で説明を省略しましたが、command-idはRunShellScript以外も指定できます。az vm run-command listを使用すると、command-idに指定可能なパラメタ一覧を参照できます。
$ az vm run-command list \
--location japaneast
[
<omitted>
{
"description": "Get the configuration of all network interfaces.",
"id": "ifconfig",
"label": "List network configuration",
"osType": "Linux",
"schema": "http://schema.management.azure.com/schemas/2016-11-17/runcommands.json"
},
{
"description": "Shows detailed information for the IP address, subnet mask and default gateway for each adapter bound to TCP/IP.",
"id": "IPConfig",
"label": "List IP configuration",
"osType": "Windows",
"schema": "http://schema.management.azure.com/schemas/2016-11-17/runcommands.json"
},
{
"description": "Checks registry settings and domain policy settings. Suggests policy actions if machine is part of a domain or modifies the settings to default values.",
"id": "RDPSettings",
"label": "Verify RDP Listener Settings",
"osType": "Windows",
"schema": "http://schema.management.azure.com/schemas/2016-11-17/runcommands.json"
},
{
"description": "Removes RunCommandLinux extension deployed to execute previous RunCommand operations.",
"id": "RemoveRunCommandLinuxExtension",
"label": "Removes the internal RunCommandLinux extension",
"osType": "Linux",
"schema": "http://schema.management.azure.com/schemas/2016-11-17/runcommands.json"
},
<omitted>
例えば、ifconfigを指定するならば、以下のようになります。
$ az vm run-command invoke \
--resource-group MyResourceGroup \
--name linux010 \
--command-id ifconfig
{
"value": [
{
"code": "ProvisioningState/succeeded",
"displayStatus": "Provisioning succeeded",
"level": "Info",
"message": "Enable succeeded: \n[stdout]\neth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500\n inet 172.16.0.10 netmask 255.255.255.0 broadcast 172.16.0.255\n inet6 fe80::20d:3aff:fe50:2270 prefixlen 64 scopeid 0x20<link>\n ether 00:0d:3a:50:22:70 txqueuelen 1000 (Ethernet)\n RX packets 98467 bytes 138425809 (132.0 MiB)\n RX errors 0 dropped 0 overruns 0 frame 0\n TX packets 9439 bytes 2086066 (1.9 MiB)\n TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0\n\nlo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536\n inet 127.0.0.1 netmask 255.0.0.0\n inet6 ::1 prefixlen 128 scopeid 0x10<host>\n loop txqueuelen 1000 (Local Loopback)\n RX packets 116 bytes 9478 (9.2 KiB)\n RX errors 0 dropped 0 overruns 0 frame 0\n TX packets 116 bytes 9478 (9.2 KiB)\n TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0\n\n\n[stderr]\n",
"time": null
}
]
}
マネージド実行コマンド
マネージド実行コマンドを使用すると、アクション実行コマンドよりも細かなコマンド実行が可能です。例えば、非同期で実行したり実行ユーザを指定したりする事ができます。
マネージド実行コマンドは「プレビュー」の扱いでサポート対象外です。「プレビュー」の取り扱いは「Microsoft Azure プレビューの追加使用条件」などを参照ください。
マネージド実行コマンドを使用するには、az vm run-command createコマンドを実行します。ヘルプを見てみると、アクション実行コマンド(az vm run-command invoke)よりも指定可能なオプションが多い事がわかります。
$ az vm run-command create -h
Command
az vm run-command create : The operation to create the run command.
Arguments
--name --run-command-name [Required] : The name of the virtual machine run command.
--resource-group -g [Required] : Name of resource group. You can configure the default
group using `az configure --defaults group=<name>`.
--vm-name [Required] : The name of the virtual machine.
--async-execution : Optional. If set to true, provisioning will complete as
soon as the script starts and will not wait for script to
complete. Allowed values: false, true.
--command-id : Specify a commandId of predefined built-in script.
--error-blob-uri : Specify the Azure storage blob where script error stream
will be uploaded.
--location -l : Location. Values from: `az account list-locations`. You
can configure the default location using `az configure
--defaults location=<location>`.
--no-wait : Do not wait for the long-running operation to finish.
--output-blob-uri : Specify the Azure storage blob where script output stream
will be uploaded.
--parameters : The parameters used by the script.
Usage: --parameters arg1=XX arg2=XX.
--protected-parameters : The parameters used by the script.
Usage: --protected-parameters credentials=somefoo secret=somebar.
--run-as-password : Password if needed for using run-as-user parameter. It
will be encrypted and not logged.
--run-as-user : By default script process runs under system/root user.
Specify custom user to host the process.
--script : Specify the script content to be executed on the VM.
--script-uri : Specify the script download location.
--tags : Space-separated tags: key[=value] [key[=value] ...]. Use
'' to clear existing tags.
--timeout-in-seconds : The timeout in seconds to execute the run command.
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: json.
--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 run command.
az vm run-command create --resource-group "myResourceGroup" --location "West US" --async-
execution false --parameters arg1=param1 arg2=value1 --run-as-password "<runAsPassword>"
--run-as-user "user1" --script "Write-Host Hello World!" --timeout-in-seconds 3600 --run-
command-name "myRunCommand" --vm-name "myVM"
To search AI knowledge base for examples, use: az find "az vm run-command create"
Please let us know how we are doing: https://aka.ms/azureclihats
例えば、以下のようにasync-executionを指定すると非同期で実行できます。
az vm run-command create \ --resource-group MyResourceGroup \ --vm-name "linux010" \ --name install \ --async-execution true \ --script "dnf install -y bind"
