Contents
Azure Service Health とサービスステータス API の概要
Azure Service Health は、サブスクリプション単位で発生する障害やメンテナンス情報をリアルタイムに取得できるサービスです。本節では Service Health のサービス別ステータス API が提供するエンドポイントと、取得できる対象(リージョン・リソースタイプ)について解説します。API を正しく呼び出すことで、独自の監視システムやレポートに組み込むことが可能です。
エンドポイントと取得対象
- 基本エンドポイントは以下の通りです。
text
GET https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.ResourceHealth/availabilityStatuses?api-version={apiVersion} {apiVersion}は公式ドキュメントで最新バージョンを必ず確認してください(例:2023‑07‑01)。古いバージョンは将来的にサポートが終了します。- パラメータ
locationを$filterクエリに組み込むことで、特定リージョンだけのステータスを取得できます。
利用例とフィルタリング
以下は東京リージョン(japaneast)のみを対象にした呼び出し例です。
|
1 2 |
GET https://management.azure.com/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/providers/Microsoft.ResourceHealth/availabilityStatuses?api-version=2023-07-01&$filter=properties/location eq 'japaneast' |
レスポンスは JSON で返り、availabilityState(Available, Degraded, Unavailable)や影響開始時刻 (impactedScope.startTime) が含まれます。
認証と権限設定:Azure AD アプリ登録とクライアントクレデンシャルフロー
Service Health API は Azure AD のアクセストークンで保護されています。本節では 安全にトークンを取得し、最小権限で API にアクセスする手順 を示します。
Azure AD アプリの作成手順
- Azure ポータル → 「Azure Active Directory」 → 「アプリ登録」 → 「新規登録」。
- 名前(例:
ServiceHealthMonitor)とサポート対象のアカウント種別を入力し、リダイレクト URI は不要です。 - 作成後に「証明書とシークレット」から クライアント シークレット を生成し、表示された値は安全な場所に保管します(コードに埋め込まない)。
必要な Application Permission と RBAC ロール
| 項目 | 推奨設定 | 補足 |
|---|---|---|
| Application Permission | Microsoft.ResourceHealth/availabilityStatuses/read(※正式名称は Azure ドキュメントで確認) |
アプリ権限なので管理者同意が必須です。 |
| RBAC ロール | サブスクリプションレベルの Reader もしくはカスタムロールに Microsoft.ResourceHealth/availabilityStatuses/read を追加 |
Reader が既に含んでいる場合は追加不要ですが、最小権限を保つために Permission のみ付与することが推奨されます。 |
注意:Permission 名は将来的に変更される可能性があります。実装前に Azure Portal の「API のアクセス許可」画面で正確な名称を必ず確認してください。
シークレット・マネージド ID の管理ベストプラクティス
- 本番環境では Azure Managed Identity を有効化し、シークレットの保管を不要にします。
- 開発・テスト環境でシークレットを使用する場合は Azure Key Vault に格納し、スクリプトからは
Get-AzKeyVaultSecretなどで取得してください。
API 呼び出し実装例:PowerShell・Azure CLI・Python
ここでは アクセストークン取得 → API リクエスト のフローを三つの言語で示します。すべて環境変数または Key Vault から機密情報を取得する想定です。
PowerShell 実装例(正しいプロパティ参照)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# 必要な環境変数をロード $tenantId = $env:AZURE_TENANT_ID $clientId = $env:AZURE_CLIENT_ID $clientSecret = $env:AZURE_CLIENT_SECRET $subscriptionId = $env:SUBSCRIPTION_ID # 1. アクセストークン取得(client_credentials フロー) $tokenResponse = Invoke-RestMethod -Method Post ` -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" ` -Body @{ client_id = $clientId scope = "https://management.azure.com/.default" client_secret = $clientSecret grant_type = "client_credentials" } $accessToken = $tokenResponse.access_token # 2. Service Health API 呼び出し $apiVersion = "2023-07-01" $uri = "https://management.azure.com/subscriptions/$subscriptionId/providers/Microsoft.ResourceHealth/availabilityStatuses?api-version=$apiVersion" $response = Invoke-RestMethod -Method Get ` -Uri $uri ` -Headers @{ Authorization = "Bearer $accessToken" Accept = "application/json" } # 3. Unavailable なリソースだけを抽出 $response.value | Where-Object { $_.properties.availabilityState -ne 'Available' } | Select-Object @{Name='Resource';Expression={$_.name}}, @{Name='State';Expression={$_.properties.availabilityState}}, @{Name='StartTime';Expression={$_.properties.impactedScope.startTime}} |
ポイント
プロパティは $_ .property の形で参照し、誤った $_.. を使用していません。
エラーハンドリングは try{} / catch{} で囲み、429(レートリミット)時は指数バックオフで再試行します。
Azure CLI 実装例(az rest の活用)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#!/usr/bin/env bash # 前提: az login が完了し、対象サブスクリプションが選択されていること SUBSCRIPTION_ID=$(az account show --query id -o tsv) API_VERSION="2023-07-01" # 1. アクセストークン取得(CLI が自動で処理) TOKEN=$(az account get-access-token \ --resource https://management.azure.com/ \ --query accessToken -o tsv) # 2. API 呼び出し az rest --method get \ --uri "https://management.azure.com/subscriptions/${SUBSCRIPTION_ID}/providers/Microsoft.ResourceHealth/availabilityStatuses?api-version=${API_VERSION}" \ --headers "Authorization=Bearer $TOKEN" "Accept=application/json" |
ポイント
* az rest は内部的に curl 相当の処理を行うため、追加ヘッダーは --header でも指定可能です。
Python 実装例(msal と requests)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
import os, time, requests from msal import ConfidentialClientApplication # 環境変数から設定取得 TENANT_ID = os.getenv("AZURE_TENANT_ID") CLIENT_ID = os.getenv("AZURE_CLIENT_ID") CLIENT_SECRET = os.getenv("AZURE_CLIENT_SECRET") SUBSCRIPTION_ID = os.getenv("AZURE_SUBSCRIPTION_ID") API_VERSION = "2023-07-01" ENDPOINT = ( f"https://management.azure.com/subscriptions/{SUBSCRIPTION_ID}" f"/providers/Microsoft.ResourceHealth/availabilityStatuses?api-version={API_VERSION}" ) # 1. トークン取得 app = ConfidentialClientApplication( client_id=CLIENT_ID, authority=f"https://login.microsoftonline.com/{TENANT_ID}", client_credential=CLIENT_SECRET, ) def acquire_token(): result = app.acquire_token_for_client(scopes=["https://management.azure.com/.default"]) if "access_token" in result: return result["access_token"] raise RuntimeError(f"Token acquisition failed: {result.get('error_description')}") # 2. API 呼び出し(指数バックオフ付き) def call_api(token, max_retry=4): headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"} for attempt in range(1, max_retry + 1): resp = requests.get(ENDPOINT, headers=headers) if resp.status_code == 200: return resp.json() if resp.status_code in (429, 503): wait = int(resp.headers.get("Retry-After", 2 ** attempt)) print(f"Retry {attempt}/{max_retry} after {wait}s (status={resp.status_code})") time.sleep(wait) else: resp.raise_for_status() raise RuntimeError("Maximum retries exceeded") if __name__ == "__main__": token = acquire_token() data = call_api(token) # Unavailable なエントリだけを表示 for item in data.get("value", []): state = item["properties"]["availabilityState"] if state != "Available": print(f"{item['name']}: {state} (Start: {item['properties']['impactedScope'].get('startTime')})") |
ポイント
* msal がトークンキャッシュと自動リフレッシュを行うため、コードがシンプルです。
取得したステータス情報の解析とエラーハンドリング
API が返す JSON は階層化された構造です。本節では 主要フィールドのマッピング表 と、代表的なエラー種別ごとのハンドリング例 を示します。
JSON フィールドマッピング表
| パス | データ型 | 意味 |
|---|---|---|
properties.availabilityState |
string (Available, Degraded, Unavailable) |
現在の稼働状態 |
properties.impactedScope.startTime |
ISO8601 datetime | 影響開始時刻 |
properties.impactedServices[*].serviceDisplayName |
string | 障害対象サービス名 |
id / name |
string | リソース識別子(サブスクリプション/リソースグループ) |
エラー種別別ハンドリング例
PowerShell
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
function Invoke-ServiceHealth { param($Uri, $Headers) $maxRetry = 5 for ($i=1; $i -le $maxRetry; $i++) { try { return Invoke-RestMethod -Method Get -Uri $Uri -Headers $Headers } catch { $status = $_.Exception.Response.StatusCode.Value__ switch ($status) { 401 { throw "認証エラー:テナント ID・シークレットを確認。" } 403 { throw "権限エラー:Microsoft.ResourceHealth/availabilityStatuses/read が付与されているか。" } 429 { $retryAfter = $_.Exception.Response.Headers["Retry-After"] $waitSec = if ($retryAfter) {[int]$retryAfter} else { [math]::Pow(2,$i) } Write-Warning "レートリミット検出:${waitSec}s 待機して再試行 ($i/$maxRetry)" Start-Sleep -Seconds $waitSec } default { if ($i -eq $maxRetry) { throw $_ } Start-Sleep -Seconds ([math]::Pow(2,$i)) } } } } } |
Python
|
1 2 3 4 5 6 7 8 9 10 |
if resp.status_code == 401: raise PermissionError("Invalid client credentials or tenant ID.") elif resp.status_code == 403: raise PermissionError("App lacks Microsoft.ResourceHealth/availabilityStatuses/read permission.") elif resp.status_code == 429: retry_after = int(resp.headers.get("Retry-After", 2 ** attempt)) time.sleep(retry_after) else: resp.raise_for_status() |
ポイント
* 401/403 は設定ミスを示すため即時通知し、429 は Retry-After ヘッダーまたは指数バックオフで再試行します。
自動化・通知連携:Log Analytics、アラート、Teams への配信と定期実行
取得したステータスを ログに蓄積し可視化、さらに 障害時に即座に担当者へ通知 するフローを構築します。ここでは Log Analytics Ingestion API の署名生成手順、Azure Monitor アラート設定例、定期実行の選択肢とベストプラクティスを示します。
Log Analytics Ingestion API の認証署名作成手順
- 必要情報
- ワークスペース ID (
$workspaceId) - 共有キー(Base64 エンコードされたシークレット)
$sharedKey - HTTP ヘッダーに必須の項目
Authorization: SharedKey <WorkspaceId>:<Signature>Log-Type: ServiceHealthStatus(任意だが大文字で 1 語)x-ms-date: <RFC1123 GMT>- 署名文字列の生成手順(PowerShell)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# ① 日付文字列を取得(GMT、RFC1123 形式) $date = (Get-Date).ToUniversalTime().ToString('r') # ② ペイロード(JSON)のバイト長 $contentLength = $payloadBytes.Length # ③ 署名対象文字列の構築 $stringToSign = "POST`n$contentLength`napplication/json`nx-ms-date:$date`n/api/logs" # ④ HMAC-SHA256 計算 $bytesToHash = [Text.Encoding]::UTF8.GetBytes($stringToSign) $keyBytes = [Convert]::FromBase64String($sharedKey) $hash = New-Object System.Security.Cryptography.HMACSHA256 $hash.Key = $keyBytes $signature = [Convert]::ToBase64String($hash.ComputeHash($bytesToHash)) # ⑤ Authorization ヘッダーの組み立て $authHeader = "SharedKey $workspaceId:$signature" |
- 最終的な API 呼び出し
|
1 2 3 4 5 6 7 8 |
Invoke-RestMethod -Method Post -Uri $uri ` -Headers @{ "Authorization" = $authHeader "Log-Type" = "ServiceHealthStatus" "x-ms-date" = $date "Content-Type" = "application/json" } -Body $payload |
この手順をスクリプト化すれば、PowerShell・Azure CLI・Python のいずれでも同様に署名生成が可能です(Python 版は hmac と hashlib を使用)。
Azure Monitor アラートと Teams Webhook 設定例
- Log Analytics のクエリベース アラート
kusto
ServiceHealthStatus
| where State != "Available"
| summarize cnt=count() by ServiceName, bin(ImpactStartTime, 5m)
| where cnt > 0 - アクション グループに Teams Webhook を追加
- Teams の「Incoming Webhook」コネクタ URL を取得し、Azure ポータルの「アラート」→「アクショングループ」→「Webhook」へ貼り付け。
- ペイロード例(Markdown 形式)
json
{
"text": "⚠️ Azure Service Health: 以下のサービスで障害が検出されました\n{{AlertContext}}"
} - 必要に応じてメールや SMS も併用し、一次対応者への確実な通知を実現します。
定期実行の選択肢とベストプラクティス
| サービス | メリット | 注意点 |
|---|---|---|
| Azure Automation Runbook (PowerShell) | 既存 PowerShell スクリプトをそのまま利用可。スケジュール UI が分かりやすい。 | ランブックは Azure AD の マネージド ID を有効化し、シークレット管理を省くことが推奨されます。 |
| Logic Apps | ノーコード/ローコードで HTTP 呼び出し・条件分岐・Teams 連携がドラッグ&ドロップで実装可能。 | 実行回数課金に注意。認証は「Managed Identity」か「API キー」設定が必要です。 |
| Azure Functions (Python / PowerShell) | サーバーレスで高速起動、Timer Trigger により柔軟な cron 表記が可能。 | 消費プランの場合は実行回数に応じ課金。常時オンが必要なら App Service プランを選択。 |
共通ベストプラクティス
- Managed Identity を利用し、Microsoft.ResourceHealth/availabilityStatuses/read のロールを割り当てるだけでシークレット不要にする。
- 再試行ポリシーは各サービスの組み込み機能(Logic Apps の「Retry Policy」や Functions の Durable Retries)を活用し、コード上の重複実装を避ける。
まとめと次のアクション
- API エンドポイントは単一でサブスクリプション全体のステータスを取得でき、最新
api-versionを必ず公式ドキュメントで確認してください。 - 認証は Azure AD アプリのクライアント クレデンシャル フローで行い、正確な Application Permission
Microsoft.ResourceHealth/availabilityStatuses/readとサブスクリプションの Reader(またはカスタム)ロールを付与します。 - PowerShell・Azure CLI・Python の実装例はプロパティ参照ミスを修正し、エラーハンドリングと指数バックオフを標準化しました。
- 取得した JSON は Log Analytics に送信し、Kusto クエリで可視化、Azure Monitor アラート+Teams Webhook で即時通知できます。署名生成手順も詳細に示しています。
- 定期実行は Azure Automation Runbook、Logic Apps、または Functions のいずれかを選択し、Managed Identity によるシークレットレス認証を推奨します。
- 過去インシデント取得やレポート作成は
startTime/endTimeフィルタと Data Factory → Power BI のパイプラインで自動化すると、MTTR や障害頻度の定量分析が容易になります。
上記手順を実環境に適用すれば、Azure Service Health の監視が コードベースで自動化され、障害検知から関係者通知まで一貫したフローが構築できます。ぜひ本稿の設定を試し、運用チームの可観測性向上に役立ててください。