サービスプリンシパルのリーダーの役割を確認する

サービスプリンシパルが Azure サブスクリプションで「Reader」ロールを保有しているかどうかを確認するには、次の Python スクリプトを使用します:

from azure.identity import DefaultAzureCredential
from azure.mgmt.authorization import AuthorizationManagementClient
from azure.core.exceptions import AzureError

def check_subscription_roles(subscription_id):
    """
    Check if subscription has Reader, Contributor, or Owner role.
    Returns True if any of these roles exist, False otherwise.
    """
    ROLE_IDS = {
        "Reader": "acdd72a7-3385-48ef-bd42-f606fba81ae7",
        "Contributor": "b24988ac-6180-42a0-ab88-20f7382dd24c",
        "Owner": "8e3af657-a8ff-443c-a75c-2fe8c4bcb635"
    }
    try:
        credential = DefaultAzureCredential()
        auth_client = AuthorizationManagementClient(credential, subscription_id)
        for assignment in auth_client.role_assignments.list_for_subscription():
            role_def_id = assignment.role_definition_id
            for role_name, role_id in ROLE_IDS.items():
                if role_id in role_def_id:
                    print(f"✓ Found {role_name} role for subscription: {subscription_id}")
                    return True  # Return immediately when any role is found
        return False  # No matching roles found
    except AzureError as e:
        print(f"Azure Error:: {e}")
        return False
    except Exception as e:
        print(f"Error:: {e}")
        return False

# Main execution
if __name__ == "__main__":
    subscription_id = "<your-subscription-id-here>"
    result = check_subscription_roles(subscription_id)
    if result:
        print("\n✓ True - Required reader role exists\n")
        exit(0)
    else:
        print("\n✗ False - No required role found\n")
        exit(1)

前提条件

お使いのオペレーティングシステムに応じて、 Python、 pip、および Azure CLI を環境にインストールしてください。 以下の残りのコマンドは、クロスプラットフォームで互換性があります。

依存関係をインストールします。

以下のコマンドを実行します。
pip3 install azure-identity azure-mgmt-authorization

サービスプリンシパルを使用してログインする

次のコマンドを実行し、プレースホルダーを自分の認証情報に置き換えてください:
az login --service-principal \
--username <client-id> \
--password <client-secret> \
--tenant <tenant-id>

前述の Python スクリプトをファイル名として保存してください。 Python スクリプト内の「 check_azure_reader.py」を、実際のサブスクリプション <your-subscription-id-here> IDに置き換えてください。 このスクリプトは、readerロールが存在するかどうかを判定し、その結果に応じて または FalseTrue 返して表示します。

スクリプトを実行する

次の Python コマンドを使用してスクリプトを実行してください:
python3 check_azure_reader.py
注:Python および pip コマンドは、お使いの環境にインストールされている Python のバージョンによって異なる場合があります(python または python3 、および pip 、または pip3)。 python3 また、 pip3Python 3 を明示的に参照してください。

トラブルシューティング

externally-managed-environment エラーで失敗した pip install 場合は、以下のコマンドを使用して仮想環境を利用してください。

  1. 仮想環境で、次のコマンドを実行してください:
    python3 -m venv azure-env
  2. 仮想環境を起動するには、次のコマンドを実行してください:
    • macOS または Linux にて:
      source azure-env/bin/activate
    • Windows の場合:
      azure-env\Scripts\activate
  3. パッケージをインストールするには、次のコマンドを実行してください:
    pip3 install azure-identity azure-mgmt-authorization
  4. スクリプトを実行するには、次のコマンドを実行してください:
    python3 check_azure_reader.py
  5. 仮想環境を無効にするには、次のコマンドを実行してください:
    deactivate