0
# Subscription Lifecycle
1
2
Individual subscription lifecycle management including cancellation, renaming, enabling, and ownership transfer operations. These operations support the complete lifecycle of Azure subscriptions with long-running operation support for complex workflows.
3
4
## Capabilities
5
6
### Cancel Subscription
7
8
Cancels an active subscription, which will disable all resources and services associated with the subscription.
9
10
```python { .api }
11
def cancel(subscription_id: str, **kwargs) -> CanceledSubscriptionId:
12
"""
13
The operation to cancel a subscription.
14
15
Args:
16
subscription_id (str): The subscription ID to cancel
17
18
Returns:
19
CanceledSubscriptionId: Confirmation of cancellation with subscription ID
20
"""
21
```
22
23
**Usage Example:**
24
25
```python
26
from azure.identity import DefaultAzureCredential
27
from azure.mgmt.subscription import SubscriptionClient
28
29
credential = DefaultAzureCredential()
30
client = SubscriptionClient(credential)
31
32
subscription_id = "12345678-1234-1234-1234-123456789012"
33
34
try:
35
result = client.subscription.cancel(subscription_id)
36
print(f"Successfully canceled subscription: {result.value}")
37
38
# Verify the cancellation by checking subscription state
39
subscription = client.subscriptions.get(subscription_id)
40
print(f"New subscription state: {subscription.state}")
41
42
except Exception as e:
43
print(f"Failed to cancel subscription: {e}")
44
```
45
46
### Rename Subscription
47
48
Changes the display name of a subscription without affecting its ID or associated resources.
49
50
```python { .api }
51
def rename(subscription_id: str, body: Union[SubscriptionName, IO], **kwargs) -> RenamedSubscriptionId:
52
"""
53
The operation to rename a subscription.
54
55
Args:
56
subscription_id (str): The subscription ID to rename
57
body (SubscriptionName): Object containing the new subscription name
58
59
Returns:
60
RenamedSubscriptionId: Confirmation of rename with subscription ID
61
"""
62
```
63
64
**Usage Example:**
65
66
```python
67
from azure.mgmt.subscription.models import SubscriptionName
68
69
subscription_id = "12345678-1234-1234-1234-123456789012"
70
new_name = "My Updated Subscription Name"
71
72
# Create the rename request
73
rename_request = SubscriptionName(subscription_name=new_name)
74
75
try:
76
result = client.subscription.rename(subscription_id, rename_request)
77
print(f"Successfully renamed subscription: {result.value}")
78
79
# Verify the rename by getting updated subscription details
80
subscription = client.subscriptions.get(subscription_id)
81
print(f"New display name: {subscription.display_name}")
82
83
except Exception as e:
84
print(f"Failed to rename subscription: {e}")
85
```
86
87
### Enable Subscription
88
89
Enables a disabled subscription, restoring access to its resources and services.
90
91
```python { .api }
92
def enable(subscription_id: str, **kwargs) -> EnabledSubscriptionId:
93
"""
94
The operation to enable a subscription.
95
96
Args:
97
subscription_id (str): The subscription ID to enable
98
99
Returns:
100
EnabledSubscriptionId: Confirmation of enablement with subscription ID
101
"""
102
```
103
104
**Usage Example:**
105
106
```python
107
subscription_id = "12345678-1234-1234-1234-123456789012"
108
109
try:
110
result = client.subscription.enable(subscription_id)
111
print(f"Successfully enabled subscription: {result.value}")
112
113
# Verify the enablement by checking subscription state
114
subscription = client.subscriptions.get(subscription_id)
115
print(f"New subscription state: {subscription.state}")
116
117
except Exception as e:
118
print(f"Failed to enable subscription: {e}")
119
```
120
121
### Accept Ownership Transfer (Long Running Operation)
122
123
Accepts ownership transfer of a subscription from another user or organization. This is a long-running operation that may take time to complete.
124
125
```python { .api }
126
def begin_accept_ownership(subscription_id: str, body: Union[AcceptOwnershipRequest, IO], **kwargs) -> LROPoller[None]:
127
"""
128
Accept subscription ownership (Long Running Operation).
129
130
Args:
131
subscription_id (str): The subscription ID for ownership transfer
132
body (AcceptOwnershipRequest): Ownership acceptance request details
133
134
Returns:
135
LROPoller[None]: Long-running operation poller for monitoring progress
136
"""
137
```
138
139
**Usage Example:**
140
141
```python
142
from azure.mgmt.subscription.models import AcceptOwnershipRequest, AcceptOwnershipRequestProperties
143
144
subscription_id = "12345678-1234-1234-1234-123456789012"
145
146
# Create ownership acceptance request
147
properties = AcceptOwnershipRequestProperties(
148
display_name="My Transferred Subscription",
149
management_group_id="/providers/Microsoft.Management/managementGroups/my-mg",
150
tags={"Environment": "Production", "Owner": "MyTeam"}
151
)
152
ownership_request = AcceptOwnershipRequest(properties=properties)
153
154
try:
155
# Start the long-running operation
156
poller = client.subscription.begin_accept_ownership(subscription_id, ownership_request)
157
print("Ownership transfer initiated. Waiting for completion...")
158
159
# Wait for completion (this may take several minutes)
160
poller.wait()
161
162
if poller.done():
163
print("Ownership transfer completed successfully")
164
165
# Check the final status
166
status = client.subscription.accept_ownership_status(subscription_id)
167
print(f"Transfer status: {status.accept_ownership_state}")
168
print(f"New subscription ID: {status.subscription_id}")
169
else:
170
print("Ownership transfer still in progress")
171
172
except Exception as e:
173
print(f"Failed to accept ownership: {e}")
174
```
175
176
### Check Ownership Transfer Status
177
178
Gets the current status of a subscription ownership transfer operation.
179
180
```python { .api }
181
def accept_ownership_status(subscription_id: str, **kwargs) -> AcceptOwnershipStatusResponse:
182
"""
183
Accept subscription ownership status.
184
185
Args:
186
subscription_id (str): The subscription ID for ownership transfer
187
188
Returns:
189
AcceptOwnershipStatusResponse: Current status of ownership transfer
190
"""
191
```
192
193
**Usage Example:**
194
195
```python
196
subscription_id = "12345678-1234-1234-1234-123456789012"
197
198
try:
199
status = client.subscription.accept_ownership_status(subscription_id)
200
print(f"Ownership State: {status.accept_ownership_state}")
201
print(f"Provisioning State: {status.provisioning_state}")
202
print(f"Billing Owner: {status.billing_owner}")
203
print(f"Subscription Tenant ID: {status.subscription_tenant_id}")
204
205
if status.subscription_id:
206
print(f"New Subscription ID: {status.subscription_id}")
207
208
except Exception as e:
209
print(f"Failed to get ownership status: {e}")
210
```
211
212
## Error Handling
213
214
Common errors and scenarios when managing subscription lifecycle:
215
216
```python
217
from azure.core.exceptions import HttpResponseError
218
219
def handle_subscription_operation_errors(operation_name: str, subscription_id: str, func, *args):
220
"""Generic error handler for subscription operations."""
221
try:
222
return func(*args)
223
except HttpResponseError as e:
224
if e.status_code == 404:
225
print(f"{operation_name}: Subscription {subscription_id} not found")
226
elif e.status_code == 403:
227
print(f"{operation_name}: Insufficient permissions for subscription {subscription_id}")
228
elif e.status_code == 409:
229
print(f"{operation_name}: Conflict - subscription may be in wrong state")
230
elif e.status_code == 400:
231
print(f"{operation_name}: Bad request - check parameters")
232
else:
233
print(f"{operation_name}: Error {e.status_code} - {e.message}")
234
raise
235
except Exception as e:
236
print(f"{operation_name}: Unexpected error - {e}")
237
raise
238
239
# Example usage
240
try:
241
result = handle_subscription_operation_errors(
242
"Cancel", subscription_id,
243
client.subscription.cancel, subscription_id
244
)
245
except Exception:
246
print("Operation failed")
247
```
248
249
## Long Running Operation Patterns
250
251
Working with long-running operations like ownership transfer:
252
253
```python
254
import time
255
from azure.core.exceptions import HttpResponseError
256
257
def monitor_ownership_transfer(client, subscription_id, poller):
258
"""Monitor ownership transfer progress with status updates."""
259
while not poller.done():
260
try:
261
# Check current status
262
status = client.subscription.accept_ownership_status(subscription_id)
263
print(f"Current state: {status.accept_ownership_state}")
264
print(f"Provisioning state: {status.provisioning_state}")
265
266
# Wait before next check
267
time.sleep(30)
268
269
except HttpResponseError as e:
270
if e.status_code == 404:
271
print("Transfer request not found or completed")
272
break
273
else:
274
print(f"Error checking status: {e}")
275
276
except KeyboardInterrupt:
277
print("Monitoring interrupted. Transfer continues in background.")
278
break
279
280
return poller.done()
281
```
282
283
## Types
284
285
```python { .api }
286
class CanceledSubscriptionId:
287
"""Result of subscription cancellation."""
288
value: str # The subscription ID that was canceled
289
290
class RenamedSubscriptionId:
291
"""Result of subscription rename."""
292
value: str # The subscription ID that was renamed
293
294
class EnabledSubscriptionId:
295
"""Result of subscription enablement."""
296
value: str # The subscription ID that was enabled
297
298
class SubscriptionName:
299
"""Request object for subscription rename."""
300
subscription_name: str # New display name for the subscription
301
302
class AcceptOwnershipRequest:
303
"""Request object for accepting subscription ownership."""
304
properties: AcceptOwnershipRequestProperties # Ownership acceptance details
305
306
class AcceptOwnershipRequestProperties:
307
"""Properties for ownership acceptance request."""
308
display_name: str # New display name for the subscription (required)
309
management_group_id: str # Management group ID to place subscription under (optional)
310
tags: Dict[str, str] # Tags to apply to the subscription (optional)
311
312
class AcceptOwnershipStatusResponse:
313
"""Response containing ownership transfer status."""
314
subscription_id: str # Newly created subscription ID (if completed)
315
accept_ownership_state: Union[str, AcceptOwnership] # Current ownership state
316
provisioning_state: Union[str, Provisioning] # Current provisioning state
317
billing_owner: str # UPN of the billing owner
318
subscription_tenant_id: str # Tenant ID of the subscription
319
tags: Dict[str, str] # Applied tags
320
```
321
322
## Enums
323
324
```python { .api }
325
class AcceptOwnership(str, Enum):
326
"""The accept ownership state of the resource."""
327
PENDING = "Pending"
328
COMPLETED = "Completed"
329
EXPIRED = "Expired"
330
331
class Provisioning(str, Enum):
332
"""The provisioning state of the resource."""
333
PENDING = "Pending"
334
ACCEPTED = "Accepted"
335
SUCCEEDED = "Succeeded"
336
```