0
# Azure Managed Service Identity Client
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: azure-mgmt-msi
7
- **Language**: Python
8
- **Installation**: `pip install azure-mgmt-msi azure-identity`
9
- **Python Support**: >=3.9
10
- **API Version**: 2024-11-30 (default), with support for 2018-11-30, 2021-09-30-preview, 2022-01-31-preview
11
12
## Core Imports
13
14
```python
15
from azure.mgmt.msi import ManagedServiceIdentityClient
16
from azure.identity import DefaultAzureCredential
17
from azure.core.credentials import TokenCredential
18
from azure.profiles import KnownProfiles
19
```
20
21
Async support:
22
23
```python
24
from azure.mgmt.msi.aio import ManagedServiceIdentityClient
25
from azure.identity.aio import DefaultAzureCredential
26
```
27
28
Models and types:
29
30
```python
31
from azure.mgmt.msi.models import (
32
Identity,
33
FederatedIdentityCredential,
34
IdentityUpdate,
35
SystemAssignedIdentity,
36
SystemData,
37
Operation,
38
OperationDisplay,
39
CreatedByType,
40
IsolationScope
41
)
42
```
43
44
## Basic Usage
45
46
```python
47
import os
48
from azure.identity import DefaultAzureCredential
49
from azure.mgmt.msi import ManagedServiceIdentityClient
50
51
# Authentication setup (requires AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET)
52
credential = DefaultAzureCredential()
53
subscription_id = os.getenv("AZURE_SUBSCRIPTION_ID")
54
55
# Initialize client
56
client = ManagedServiceIdentityClient(
57
credential=credential,
58
subscription_id=subscription_id
59
)
60
61
# Create a user-assigned identity
62
identity = client.user_assigned_identities.create_or_update(
63
resource_group_name="myResourceGroup",
64
resource_name="myIdentity",
65
parameters={
66
"location": "eastus",
67
"tags": {"environment": "production"}
68
}
69
)
70
71
print(f"Created identity: {identity.name}")
72
print(f"Client ID: {identity.client_id}")
73
print(f"Principal ID: {identity.principal_id}")
74
75
# List all identities in subscription
76
for identity in client.user_assigned_identities.list_by_subscription():
77
print(f"Identity: {identity.name}, Location: {identity.location}")
78
79
# Get system-assigned identity for a resource
80
scope = "subscriptions/sub-id/resourceGroups/rg-name/providers/Microsoft.Compute/virtualMachines/vm-name"
81
system_identity = client.system_assigned_identities.get_by_scope(scope=scope)
82
```
83
84
## Architecture
85
86
The azure-mgmt-msi library follows Azure SDK design patterns with operation groups managing different identity types:
87
88
- **ManagedServiceIdentityClient**: Main client providing access to operation groups using the multi-API client pattern
89
- **UserAssignedIdentitiesOperations**: User-assigned identity lifecycle management
90
- **SystemAssignedIdentitiesOperations**: System-assigned identity retrieval
91
- **FederatedIdentityCredentialsOperations**: Federated identity credential management for workload identity scenarios (available from API version 2022-01-31-preview+)
92
- **Operations**: Service operation discovery
93
94
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.
95
96
## API Version Support
97
98
- **2018-11-30** (GA): Basic user/system-assigned identity operations
99
- **2021-09-30-preview**: Same as 2018-11-30
100
- **2022-01-31-preview**: Added federated identity credentials
101
- **2024-11-30** (Default, GA): Added isolation scope, SystemData metadata, enhanced models
102
103
## Capabilities
104
105
### User-Assigned Identity Management
106
107
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.
108
109
```python { .api }
110
def create_or_update(resource_group_name: str, resource_name: str, parameters: Union[Identity, IO[bytes]], **kwargs) -> Identity
111
def get(resource_group_name: str, resource_name: str, **kwargs) -> Identity
112
def update(resource_group_name: str, resource_name: str, parameters: Union[IdentityUpdate, IO[bytes]], **kwargs) -> Identity
113
def delete(resource_group_name: str, resource_name: str, **kwargs) -> None
114
def list_by_subscription(**kwargs) -> ItemPaged[Identity]
115
def list_by_resource_group(resource_group_name: str, **kwargs) -> ItemPaged[Identity]
116
```
117
118
[User-Assigned Identities](./user-assigned-identities.md)
119
120
### System-Assigned Identity Access
121
122
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.
123
124
```python { .api }
125
def get_by_scope(scope: str, **kwargs) -> SystemAssignedIdentity
126
```
127
128
[System-Assigned Identities](./system-assigned-identities.md)
129
130
### Federated Identity Credentials
131
132
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.
133
134
```python { .api }
135
def create_or_update(resource_group_name: str, resource_name: str,
136
federated_identity_credential_resource_name: str,
137
parameters: Union[FederatedIdentityCredential, IO[bytes]], **kwargs) -> FederatedIdentityCredential
138
def get(resource_group_name: str, resource_name: str,
139
federated_identity_credential_resource_name: str, **kwargs) -> FederatedIdentityCredential
140
def delete(resource_group_name: str, resource_name: str,
141
federated_identity_credential_resource_name: str, **kwargs) -> None
142
def list(resource_group_name: str, resource_name: str,
143
top: Optional[int] = None, skiptoken: Optional[str] = None, **kwargs) -> ItemPaged[FederatedIdentityCredential]
144
```
145
146
[Federated Identity Credentials](./federated-identity-credentials.md)
147
148
### Service Operations
149
150
Discovery of available operations for the Microsoft.ManagedIdentity resource provider, useful for API exploration and service capability validation.
151
152
```python { .api }
153
def list(**kwargs) -> ItemPaged[Operation]
154
```
155
156
## Client Configuration
157
158
```python { .api }
159
class ManagedServiceIdentityClient:
160
def __init__(
161
self,
162
credential: TokenCredential,
163
subscription_id: str,
164
api_version: Optional[str] = None,
165
base_url: Optional[str] = None,
166
profile: KnownProfiles = KnownProfiles.default,
167
**kwargs
168
)
169
```
170
171
**Parameters:**
172
- `credential`: Azure credential object (from azure-identity)
173
- `subscription_id`: Azure subscription ID
174
- `api_version`: API version override (defaults to "2024-11-30")
175
- `base_url`: Service URL override (defaults to Azure public cloud)
176
- `profile`: Profile definition for multi-cloud support
177
178
## Core Types
179
180
```python { .api }
181
class Identity:
182
"""User-assigned managed identity resource (extends TrackedResource)."""
183
# Read-only properties
184
id: str # Full Azure resource ID (read-only)
185
name: str # Resource name (read-only)
186
type: str # Resource type (read-only)
187
system_data: SystemData # ARM metadata (read-only)
188
tenant_id: str # Azure tenant ID (read-only)
189
principal_id: str # Service principal ID (read-only)
190
client_id: str # Application client ID (read-only)
191
192
# Configurable properties
193
location: str # Azure region (required)
194
tags: Dict[str, str] # Resource tags (optional)
195
isolation_scope: IsolationScope # Regional isolation: "None" or "Regional" (optional)
196
197
class SystemAssignedIdentity:
198
"""System-assigned managed identity resource (extends ProxyResource)."""
199
# Read-only properties
200
id: str # Full Azure resource ID (read-only)
201
name: str # Resource name (read-only)
202
type: str # Resource type (read-only)
203
system_data: SystemData # ARM metadata (read-only)
204
tenant_id: str # Azure tenant ID (read-only)
205
principal_id: str # Service principal ID (read-only)
206
client_id: str # Application client ID (read-only)
207
client_secret_url: str # ManagedServiceIdentity DataPlane URL (read-only)
208
209
# Required properties
210
location: str # Azure region (required)
211
tags: Dict[str, str] # Resource tags (optional)
212
213
class FederatedIdentityCredential:
214
"""Federated identity credential for workload identity federation (extends ProxyResource)."""
215
# Read-only properties
216
id: str # Full Azure resource ID (read-only)
217
name: str # Resource name (read-only)
218
type: str # Resource type (read-only)
219
system_data: SystemData # ARM metadata (read-only)
220
221
# Configurable properties
222
issuer: str # OIDC issuer URL (required)
223
subject: str # External identity identifier (required)
224
audiences: List[str] # Token audiences (required)
225
226
class IdentityUpdate:
227
"""Update parameters for user-assigned identity."""
228
# Read-only properties
229
id: str # Resource ID (read-only)
230
name: str # Resource name (read-only)
231
type: str # Resource type (read-only)
232
system_data: SystemData # ARM metadata (read-only)
233
tenant_id: str # Azure tenant ID (read-only)
234
principal_id: str # Service principal ID (read-only)
235
client_id: str # Application client ID (read-only)
236
237
# Configurable properties
238
location: str # Updated location (optional)
239
tags: Dict[str, str] # Updated resource tags (optional)
240
isolation_scope: IsolationScope # Regional isolation setting (optional)
241
```
242
243
## Enums
244
245
```python { .api }
246
class CreatedByType(str, Enum):
247
"""Resource creator type."""
248
USER = "User"
249
APPLICATION = "Application"
250
MANAGED_IDENTITY = "ManagedIdentity"
251
KEY = "Key"
252
253
class IsolationScope(str, Enum):
254
"""Regional isolation scope for identities."""
255
NONE = "None"
256
REGIONAL = "Regional"
257
258
class SystemData:
259
"""ARM metadata containing createdBy and modifiedBy information."""
260
created_by: str # Identity that created the resource
261
created_by_type: CreatedByType # Type of identity that created the resource
262
created_at: datetime # Timestamp of resource creation
263
last_modified_by: str # Identity that last modified the resource
264
last_modified_by_type: CreatedByType # Type of identity that last modified
265
last_modified_at: datetime # Timestamp of last modification
266
267
class Operation:
268
"""Available operation for Microsoft.ManagedIdentity provider."""
269
name: str # Operation name (format: {provider}/{resource}/{operation})
270
display: OperationDisplay # Operation display information
271
272
class OperationDisplay:
273
"""Display information for an operation."""
274
provider: str # Friendly name of resource provider
275
operation: str # Type of operation (read, write, delete)
276
resource: str # Resource type
277
description: str # Description of the operation
278
```
279
280
## Authentication Requirements
281
282
The client requires Azure Active Directory authentication using the `azure-identity` library. Common authentication patterns:
283
284
```python
285
from azure.identity import DefaultAzureCredential, ClientSecretCredential
286
287
# Default credential (recommended for production)
288
credential = DefaultAzureCredential()
289
290
# Service principal authentication
291
credential = ClientSecretCredential(
292
tenant_id="your-tenant-id",
293
client_id="your-client-id",
294
client_secret="your-client-secret"
295
)
296
```
297
298
**Required Environment Variables for DefaultAzureCredential:**
299
- `AZURE_CLIENT_ID`: Application client ID
300
- `AZURE_TENANT_ID`: Azure tenant ID
301
- `AZURE_CLIENT_SECRET`: Application client secret
302
- `AZURE_SUBSCRIPTION_ID`: Target subscription ID
303
304
## Parameter Constraints
305
306
The API enforces validation constraints on various parameters:
307
308
**Resource Names:**
309
- `resource_group_name`: 1-90 characters, pattern: `^[a-zA-Z0-9._()\-]*[a-zA-Z0-9_()]$`
310
- `federated_identity_credential_resource_name`: 3-120 characters, pattern: `^[a-zA-Z0-9]{1}[a-zA-Z0-9-_]{2,119}$`
311
312
**Pagination:**
313
- `top`: Maximum number of items to return per page
314
- `skiptoken`: Token for retrieving the next page of results
315
316
**Model Validation:**
317
- `issuer`: Must be HTTPS URL for federated credentials
318
- `audiences`: Typically includes "api://AzureADTokenExchange"
319
- `location`: Must be valid Azure region
320
321
## Error Handling
322
323
```python
324
from azure.core.exceptions import (
325
ClientAuthenticationError,
326
HttpResponseError,
327
ResourceExistsError,
328
ResourceNotFoundError
329
)
330
331
try:
332
identity = client.user_assigned_identities.get(
333
resource_group_name="myResourceGroup",
334
resource_name="myIdentity"
335
)
336
except ResourceNotFoundError:
337
print("Identity not found")
338
except ClientAuthenticationError:
339
print("Authentication failed")
340
except HttpResponseError as e:
341
print(f"HTTP error: {e.status_code} - {e.message}")
342
```