CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-azure-mgmt-msi

Microsoft Azure Managed Service Identity Management Client Library for Python

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

index.mddocs/

Azure Managed Service Identity Client

A comprehensive Python client library for managing Azure Managed Service Identity (MSI) resources through the Azure Resource Manager REST API. This library provides programmatic access to create, configure, and manage user-assigned and system-assigned managed identities, enabling secure authentication and authorization for Azure resources without storing credentials in code.

Package Information

  • Package Name: azure-mgmt-msi
  • Language: Python
  • Installation: pip install azure-mgmt-msi azure-identity
  • Python Support: >=3.9
  • API Version: 2024-11-30 (default), with support for 2018-11-30, 2021-09-30-preview, 2022-01-31-preview

Core Imports

from azure.mgmt.msi import ManagedServiceIdentityClient
from azure.identity import DefaultAzureCredential
from azure.core.credentials import TokenCredential
from azure.profiles import KnownProfiles

Async support:

from azure.mgmt.msi.aio import ManagedServiceIdentityClient
from azure.identity.aio import DefaultAzureCredential

Models and types:

from azure.mgmt.msi.models import (
    Identity, 
    FederatedIdentityCredential, 
    IdentityUpdate,
    SystemAssignedIdentity,
    SystemData,
    Operation,
    OperationDisplay,
    CreatedByType,
    IsolationScope
)

Basic Usage

import os
from azure.identity import DefaultAzureCredential
from azure.mgmt.msi import ManagedServiceIdentityClient

# Authentication setup (requires AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET)
credential = DefaultAzureCredential()
subscription_id = os.getenv("AZURE_SUBSCRIPTION_ID")

# Initialize client
client = ManagedServiceIdentityClient(
    credential=credential,
    subscription_id=subscription_id
)

# Create a user-assigned identity
identity = client.user_assigned_identities.create_or_update(
    resource_group_name="myResourceGroup",
    resource_name="myIdentity",
    parameters={
        "location": "eastus",
        "tags": {"environment": "production"}
    }
)

print(f"Created identity: {identity.name}")
print(f"Client ID: {identity.client_id}")
print(f"Principal ID: {identity.principal_id}")

# List all identities in subscription
for identity in client.user_assigned_identities.list_by_subscription():
    print(f"Identity: {identity.name}, Location: {identity.location}")

# Get system-assigned identity for a resource
scope = "subscriptions/sub-id/resourceGroups/rg-name/providers/Microsoft.Compute/virtualMachines/vm-name"
system_identity = client.system_assigned_identities.get_by_scope(scope=scope)

Architecture

The azure-mgmt-msi library follows Azure SDK design patterns with operation groups managing different identity types:

  • ManagedServiceIdentityClient: Main client providing access to operation groups using the multi-API client pattern
  • UserAssignedIdentitiesOperations: User-assigned identity lifecycle management
  • SystemAssignedIdentitiesOperations: System-assigned identity retrieval
  • FederatedIdentityCredentialsOperations: Federated identity credential management for workload identity scenarios (available from API version 2022-01-31-preview+)
  • Operations: Service operation discovery

The library supports both synchronous and asynchronous operations, multi-API versioning, and follows Azure core patterns for authentication, error handling, and pagination. All create/update operations accept both model objects and IO[bytes] for raw JSON input. All list operations return ItemPaged objects for automatic pagination handling.

API Version Support

  • 2018-11-30 (GA): Basic user/system-assigned identity operations
  • 2021-09-30-preview: Same as 2018-11-30
  • 2022-01-31-preview: Added federated identity credentials
  • 2024-11-30 (Default, GA): Added isolation scope, SystemData metadata, enhanced models

Capabilities

User-Assigned Identity Management

Comprehensive lifecycle management for user-assigned managed identities including creation, updates, retrieval, deletion, and listing operations. User-assigned identities provide reusable managed identities that can be assigned to multiple Azure resources.

def create_or_update(resource_group_name: str, resource_name: str, parameters: Union[Identity, IO[bytes]], **kwargs) -> Identity
def get(resource_group_name: str, resource_name: str, **kwargs) -> Identity  
def update(resource_group_name: str, resource_name: str, parameters: Union[IdentityUpdate, IO[bytes]], **kwargs) -> Identity
def delete(resource_group_name: str, resource_name: str, **kwargs) -> None
def list_by_subscription(**kwargs) -> ItemPaged[Identity]
def list_by_resource_group(resource_group_name: str, **kwargs) -> ItemPaged[Identity]

User-Assigned Identities

System-Assigned Identity Access

Retrieval of system-assigned managed identities that are automatically created and managed by Azure services. System-assigned identities have a lifecycle tied to the resource that creates them.

def get_by_scope(scope: str, **kwargs) -> SystemAssignedIdentity

System-Assigned Identities

Federated Identity Credentials

Management of federated identity credentials that enable workload identity federation, allowing external identity providers (like Kubernetes service accounts) to obtain Azure tokens without storing long-lived secrets.

def create_or_update(resource_group_name: str, resource_name: str, 
                    federated_identity_credential_resource_name: str, 
                    parameters: Union[FederatedIdentityCredential, IO[bytes]], **kwargs) -> FederatedIdentityCredential
def get(resource_group_name: str, resource_name: str, 
        federated_identity_credential_resource_name: str, **kwargs) -> FederatedIdentityCredential
def delete(resource_group_name: str, resource_name: str, 
           federated_identity_credential_resource_name: str, **kwargs) -> None
def list(resource_group_name: str, resource_name: str, 
         top: Optional[int] = None, skiptoken: Optional[str] = None, **kwargs) -> ItemPaged[FederatedIdentityCredential]

Federated Identity Credentials

Service Operations

Discovery of available operations for the Microsoft.ManagedIdentity resource provider, useful for API exploration and service capability validation.

def list(**kwargs) -> ItemPaged[Operation]

Client Configuration

class ManagedServiceIdentityClient:
    def __init__(
        self,
        credential: TokenCredential,
        subscription_id: str,
        api_version: Optional[str] = None,
        base_url: Optional[str] = None,
        profile: KnownProfiles = KnownProfiles.default,
        **kwargs
    )

Parameters:

  • credential: Azure credential object (from azure-identity)
  • subscription_id: Azure subscription ID
  • api_version: API version override (defaults to "2024-11-30")
  • base_url: Service URL override (defaults to Azure public cloud)
  • profile: Profile definition for multi-cloud support

Core Types

class Identity:
    """User-assigned managed identity resource (extends TrackedResource)."""
    # Read-only properties
    id: str                         # Full Azure resource ID (read-only)
    name: str                       # Resource name (read-only)
    type: str                       # Resource type (read-only)
    system_data: SystemData         # ARM metadata (read-only)
    tenant_id: str                  # Azure tenant ID (read-only)
    principal_id: str               # Service principal ID (read-only)
    client_id: str                  # Application client ID (read-only)
    
    # Configurable properties
    location: str                   # Azure region (required)
    tags: Dict[str, str]            # Resource tags (optional)
    isolation_scope: IsolationScope # Regional isolation: "None" or "Regional" (optional)

class SystemAssignedIdentity:
    """System-assigned managed identity resource (extends ProxyResource)."""
    # Read-only properties
    id: str                         # Full Azure resource ID (read-only)
    name: str                       # Resource name (read-only)
    type: str                       # Resource type (read-only)
    system_data: SystemData         # ARM metadata (read-only)
    tenant_id: str                  # Azure tenant ID (read-only)
    principal_id: str               # Service principal ID (read-only)
    client_id: str                  # Application client ID (read-only)
    client_secret_url: str          # ManagedServiceIdentity DataPlane URL (read-only)
    
    # Required properties
    location: str                   # Azure region (required)
    tags: Dict[str, str]            # Resource tags (optional)

class FederatedIdentityCredential:
    """Federated identity credential for workload identity federation (extends ProxyResource)."""
    # Read-only properties
    id: str                         # Full Azure resource ID (read-only)
    name: str                       # Resource name (read-only)
    type: str                       # Resource type (read-only)
    system_data: SystemData         # ARM metadata (read-only)
    
    # Configurable properties
    issuer: str                     # OIDC issuer URL (required)
    subject: str                    # External identity identifier (required)
    audiences: List[str]            # Token audiences (required)

class IdentityUpdate:
    """Update parameters for user-assigned identity."""
    # Read-only properties
    id: str                         # Resource ID (read-only)
    name: str                       # Resource name (read-only)
    type: str                       # Resource type (read-only)
    system_data: SystemData         # ARM metadata (read-only)
    tenant_id: str                  # Azure tenant ID (read-only)
    principal_id: str               # Service principal ID (read-only)
    client_id: str                  # Application client ID (read-only)
    
    # Configurable properties
    location: str                   # Updated location (optional)
    tags: Dict[str, str]            # Updated resource tags (optional)
    isolation_scope: IsolationScope # Regional isolation setting (optional)

Enums

class CreatedByType(str, Enum):
    """Resource creator type."""
    USER = "User"
    APPLICATION = "Application"
    MANAGED_IDENTITY = "ManagedIdentity"
    KEY = "Key"

class IsolationScope(str, Enum):
    """Regional isolation scope for identities."""
    NONE = "None"
    REGIONAL = "Regional"

class SystemData:
    """ARM metadata containing createdBy and modifiedBy information."""
    created_by: str                     # Identity that created the resource
    created_by_type: CreatedByType      # Type of identity that created the resource
    created_at: datetime                # Timestamp of resource creation
    last_modified_by: str               # Identity that last modified the resource
    last_modified_by_type: CreatedByType # Type of identity that last modified
    last_modified_at: datetime          # Timestamp of last modification

class Operation:
    """Available operation for Microsoft.ManagedIdentity provider."""
    name: str                           # Operation name (format: {provider}/{resource}/{operation})
    display: OperationDisplay           # Operation display information

class OperationDisplay:
    """Display information for an operation."""
    provider: str                       # Friendly name of resource provider
    operation: str                      # Type of operation (read, write, delete)
    resource: str                       # Resource type
    description: str                    # Description of the operation

Authentication Requirements

The client requires Azure Active Directory authentication using the azure-identity library. Common authentication patterns:

from azure.identity import DefaultAzureCredential, ClientSecretCredential

# Default credential (recommended for production)
credential = DefaultAzureCredential()

# Service principal authentication
credential = ClientSecretCredential(
    tenant_id="your-tenant-id",
    client_id="your-client-id", 
    client_secret="your-client-secret"
)

Required Environment Variables for DefaultAzureCredential:

  • AZURE_CLIENT_ID: Application client ID
  • AZURE_TENANT_ID: Azure tenant ID
  • AZURE_CLIENT_SECRET: Application client secret
  • AZURE_SUBSCRIPTION_ID: Target subscription ID

Parameter Constraints

The API enforces validation constraints on various parameters:

Resource Names:

  • resource_group_name: 1-90 characters, pattern: ^[a-zA-Z0-9._()\-]*[a-zA-Z0-9_()]$
  • federated_identity_credential_resource_name: 3-120 characters, pattern: ^[a-zA-Z0-9]{1}[a-zA-Z0-9-_]{2,119}$

Pagination:

  • top: Maximum number of items to return per page
  • skiptoken: Token for retrieving the next page of results

Model Validation:

  • issuer: Must be HTTPS URL for federated credentials
  • audiences: Typically includes "api://AzureADTokenExchange"
  • location: Must be valid Azure region

Error Handling

from azure.core.exceptions import (
    ClientAuthenticationError,
    HttpResponseError,
    ResourceExistsError,
    ResourceNotFoundError
)

try:
    identity = client.user_assigned_identities.get(
        resource_group_name="myResourceGroup",
        resource_name="myIdentity"
    )
except ResourceNotFoundError:
    print("Identity not found")
except ClientAuthenticationError:
    print("Authentication failed")
except HttpResponseError as e:
    print(f"HTTP error: {e.status_code} - {e.message}")

Install with Tessl CLI

npx tessl i tessl/pypi-azure-mgmt-msi

docs

federated-identity-credentials.md

index.md

system-assigned-identities.md

user-assigned-identities.md

tile.json