⌨️

Invoke-AzRestMethod の使い方

2025/01/21に公開

はじめに

Azure CLI や PowerShell が対応していないリソースや設定の場合、Azure の REST API を直接叩くケースがあります。Azure の REST API を使用する場合には Bearer トークンの管理が面倒なので、Invoke-AzRestMethod を使うのですが、使い方をよく忘れてしまうのでメモです。

使い方

公開ドキュメントはこちらです。
https://learn.microsoft.com/ja-jp/powershell/azure/manage-azure-resources-invoke-azrestmethod?view=azps-12.5.0

こちらは Method などを含めすべてパラメータに指定する方式なのですが、こちらだと PUT や GET を切り替えて実行するのが面倒なので、 URI や Method を個別に指定する方法を利用しています。

今回は Log Analytics ワークスペースの専用クラスターを作成する方法を例としていますが、考え方は基本的に同じで、

  • -Path で ResourceID と API バージョンを指定
  • -Method の指定で
    • GET = 参照
    • POST or PUT = デプロイ (API により異なる)
    • POST or PUT or PATCH = 更新 (API によりことなる)
    • DELETE = 削除
  • POST や PUT、PATCH の場合、-Payload でリソースのパラメータを指定

作成

# パラメーターを指定
$subscriptionId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
$resourceGroupName = "myrg"
$resourceName = "mylawscluster"

# path を指定
$path = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.OperationalInsights/clusters/$($resourceName)?api-version=2022-10-01"

# REST API の body を作成
$payload = @{
    "identity" = @{
        "type"= "systemAssigned"
    }
    "sku"= @{
        "name" = "capacityReservation"
        "Capacity" = 100
    }
    "properties"= @{
        "billingType"= "Cluster"
    }
    "location"= "japaneast"
} | ConvertTo-Json

# Azure PowerShell に接続
Connect-AzAccount -SubscriptionId $subscriptionId

# REST API を実行
$response = Invoke-AzRestMethod -Path $path -Method Put -Payload $payload

# 実行結果の確認
$response

参照

### 以下は事前に実行済みであれば不要 ### 
# パラメーターを指定
$subscriptionId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
$resourceGroupName = "myrg"
$resourceName = "mylawscluster"

# path を指定
$path = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.OperationalInsights/clusters/$($resourceName)?api-version=2022-10-01"

# Azure PowerShell に接続
Connect-AzAccount -SubscriptionId $subscriptionId
### ここまで ###

# REST API を実行
$response = Invoke-AzRestMethod -Path $path -Method Get

# 実行結果の確認
$response

削除

### 以下は事前に実行済みであれば不要 ### 
# パラメーターを指定
$subscriptionId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
$resourceGroupName = "myrg"
$resourceName = "mylawscluster"

# path を指定
$path = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.OperationalInsights/clusters/$($resourceName)?api-version=2022-10-01"

# Azure PowerShell に接続
Connect-AzAccount -SubscriptionId $subscriptionId
### ここまで ### 

# REST API を実行
$response = Invoke-AzRestMethod -Path $path -Method Delete

# 実行結果の確認
$response
Microsoft (有志)

Discussion