Microsoft Azure Managed Service Identity Management Client Library for Python
npx @tessl/cli install tessl/pypi-azure-mgmt-msi@7.1.0A 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.
pip install azure-mgmt-msi azure-identityfrom azure.mgmt.msi import ManagedServiceIdentityClient
from azure.identity import DefaultAzureCredential
from azure.core.credentials import TokenCredential
from azure.profiles import KnownProfilesAsync support:
from azure.mgmt.msi.aio import ManagedServiceIdentityClient
from azure.identity.aio import DefaultAzureCredentialModels and types:
from azure.mgmt.msi.models import (
Identity,
FederatedIdentityCredential,
IdentityUpdate,
SystemAssignedIdentity,
SystemData,
Operation,
OperationDisplay,
CreatedByType,
IsolationScope
)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)The azure-mgmt-msi library follows Azure SDK design patterns with operation groups managing different identity types:
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.
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]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) -> SystemAssignedIdentityManagement 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
Discovery of available operations for the Microsoft.ManagedIdentity resource provider, useful for API exploration and service capability validation.
def list(**kwargs) -> ItemPaged[Operation]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 IDapi_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 supportclass 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)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 operationThe 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 IDAZURE_TENANT_ID: Azure tenant IDAZURE_CLIENT_SECRET: Application client secretAZURE_SUBSCRIPTION_ID: Target subscription IDThe 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 pageskiptoken: Token for retrieving the next page of resultsModel Validation:
issuer: Must be HTTPS URL for federated credentialsaudiences: Typically includes "api://AzureADTokenExchange"location: Must be valid Azure regionfrom 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}")