0
# Subnet Service Association Links
1
2
Subnet Service Association Links manage the relationship between Azure Container Instances and virtual network subnets. These operations allow you to control container group integration with virtual networks and clean up network associations when no longer needed.
3
4
## Capabilities
5
6
### Delete Subnet Service Association Link { .api }
7
8
```python
9
def begin_delete(
10
resource_group_name: str,
11
virtual_network_name: str,
12
subnet_name: str,
13
service_association_link_name: str,
14
**kwargs
15
) -> LROPoller[None]:
16
"""
17
Delete a subnet service association link.
18
19
Args:
20
resource_group_name (str): Name of the resource group containing the virtual network
21
virtual_network_name (str): Name of the virtual network
22
subnet_name (str): Name of the subnet
23
service_association_link_name (str): Name of the service association link to delete
24
25
Returns:
26
LROPoller[None]: Long-running operation poller for the deletion
27
28
Example:
29
# Delete a subnet service association link
30
delete_operation = client.subnet_service_association_link.begin_delete(
31
resource_group_name="my-resource-group",
32
virtual_network_name="my-vnet",
33
subnet_name="container-subnet",
34
service_association_link_name="my-container-group-link"
35
)
36
37
# Wait for deletion to complete
38
delete_operation.result()
39
print("Subnet service association link deleted successfully")
40
"""
41
```
42
43
## Usage Examples
44
45
### Clean Up Container Group Network Associations
46
47
```python
48
def cleanup_container_group_network_associations(
49
client,
50
resource_group_name,
51
virtual_network_name,
52
subnet_name,
53
container_group_names
54
):
55
"""
56
Clean up subnet service association links for multiple container groups.
57
58
Args:
59
client: ContainerInstanceManagementClient instance
60
resource_group_name (str): Resource group name
61
virtual_network_name (str): Virtual network name
62
subnet_name (str): Subnet name
63
container_group_names (List[str]): List of container group names to clean up
64
65
Returns:
66
List[dict]: Results of cleanup operations
67
"""
68
69
cleanup_results = []
70
71
for container_group_name in container_group_names:
72
try:
73
# Generate service association link name (typically matches container group name)
74
link_name = f"{container_group_name}-link"
75
76
print(f"Deleting subnet association for container group: {container_group_name}")
77
78
# Delete the service association link
79
delete_operation = client.subnet_service_association_link.begin_delete(
80
resource_group_name=resource_group_name,
81
virtual_network_name=virtual_network_name,
82
subnet_name=subnet_name,
83
service_association_link_name=link_name
84
)
85
86
# Wait for completion
87
delete_operation.result()
88
89
cleanup_results.append({
90
'container_group': container_group_name,
91
'link_name': link_name,
92
'status': 'success',
93
'message': 'Subnet association link deleted successfully'
94
})
95
96
except Exception as e:
97
cleanup_results.append({
98
'container_group': container_group_name,
99
'link_name': link_name,
100
'status': 'error',
101
'message': str(e)
102
})
103
104
return cleanup_results
105
106
# Usage
107
container_groups_to_cleanup = [
108
"web-app-container-group",
109
"api-container-group",
110
"worker-container-group"
111
]
112
113
results = cleanup_container_group_network_associations(
114
client=client,
115
resource_group_name="production-rg",
116
virtual_network_name="production-vnet",
117
subnet_name="container-subnet",
118
container_group_names=container_groups_to_cleanup
119
)
120
121
# Report results
122
print("Cleanup Results:")
123
for result in results:
124
status_symbol = "✅" if result['status'] == 'success' else "❌"
125
print(f"{status_symbol} {result['container_group']}: {result['message']}")
126
```
127
128
### Bulk Network Cleanup After Container Group Deletion
129
130
```python
131
import time
132
133
def bulk_network_cleanup_after_deletion(
134
client,
135
resource_group_name,
136
virtual_network_name,
137
subnet_name,
138
container_group_operations
139
):
140
"""
141
Perform network cleanup after bulk container group deletion.
142
143
Args:
144
client: ContainerInstanceManagementClient instance
145
resource_group_name (str): Resource group name
146
virtual_network_name (str): Virtual network name
147
subnet_name (str): Subnet name
148
container_group_operations (List[dict]): List of container group deletion operations
149
150
Returns:
151
dict: Summary of cleanup operations
152
"""
153
154
print("Waiting for container group deletions to complete...")
155
156
# Wait for all container group deletions to complete first
157
successful_deletions = []
158
failed_deletions = []
159
160
for operation_info in container_group_operations:
161
try:
162
# Wait for the container group deletion to complete
163
operation_info['operation'].result()
164
successful_deletions.append(operation_info['name'])
165
print(f"✅ Container group '{operation_info['name']}' deleted successfully")
166
except Exception as e:
167
failed_deletions.append({
168
'name': operation_info['name'],
169
'error': str(e)
170
})
171
print(f"❌ Failed to delete container group '{operation_info['name']}': {e}")
172
173
print(f"\nContainer group deletions complete: {len(successful_deletions)} successful, {len(failed_deletions)} failed")
174
175
# Now clean up subnet associations for successfully deleted container groups
176
if successful_deletions:
177
print("\nCleaning up subnet service association links...")
178
179
network_cleanup_results = cleanup_container_group_network_associations(
180
client=client,
181
resource_group_name=resource_group_name,
182
virtual_network_name=virtual_network_name,
183
subnet_name=subnet_name,
184
container_group_names=successful_deletions
185
)
186
187
successful_network_cleanup = [r for r in network_cleanup_results if r['status'] == 'success']
188
failed_network_cleanup = [r for r in network_cleanup_results if r['status'] == 'error']
189
190
print(f"Network cleanup complete: {len(successful_network_cleanup)} successful, {len(failed_network_cleanup)} failed")
191
192
return {
193
'container_group_deletions': {
194
'successful': successful_deletions,
195
'failed': failed_deletions
196
},
197
'network_cleanup': {
198
'successful': successful_network_cleanup,
199
'failed': failed_network_cleanup
200
},
201
'summary': {
202
'total_operations': len(container_group_operations),
203
'fully_completed': len(successful_network_cleanup),
204
'partial_failures': len(successful_deletions) - len(successful_network_cleanup),
205
'complete_failures': len(failed_deletions)
206
}
207
}
208
209
return {
210
'container_group_deletions': {
211
'successful': [],
212
'failed': failed_deletions
213
},
214
'network_cleanup': {
215
'successful': [],
216
'failed': []
217
},
218
'summary': {
219
'total_operations': len(container_group_operations),
220
'fully_completed': 0,
221
'partial_failures': 0,
222
'complete_failures': len(failed_deletions)
223
}
224
}
225
226
# Example usage
227
# First, start container group deletions
228
container_group_names = ["app1-cg", "app2-cg", "app3-cg"]
229
deletion_operations = []
230
231
for cg_name in container_group_names:
232
try:
233
operation = client.container_groups.begin_delete(
234
resource_group_name="production-rg",
235
container_group_name=cg_name
236
)
237
deletion_operations.append({
238
'name': cg_name,
239
'operation': operation
240
})
241
print(f"Started deletion of container group: {cg_name}")
242
except Exception as e:
243
print(f"Failed to start deletion of {cg_name}: {e}")
244
245
# Then perform bulk cleanup
246
if deletion_operations:
247
cleanup_summary = bulk_network_cleanup_after_deletion(
248
client=client,
249
resource_group_name="production-rg",
250
virtual_network_name="production-vnet",
251
subnet_name="container-subnet",
252
container_group_operations=deletion_operations
253
)
254
255
print("\n=== Cleanup Summary ===")
256
print(f"Total operations: {cleanup_summary['summary']['total_operations']}")
257
print(f"Fully completed: {cleanup_summary['summary']['fully_completed']}")
258
print(f"Partial failures: {cleanup_summary['summary']['partial_failures']}")
259
print(f"Complete failures: {cleanup_summary['summary']['complete_failures']}")
260
```
261
262
### Network Integration Troubleshooting
263
264
```python
265
def troubleshoot_network_integration(
266
client,
267
resource_group_name,
268
container_group_name,
269
virtual_network_name,
270
subnet_name
271
):
272
"""
273
Troubleshoot network integration issues for a container group.
274
275
Args:
276
client: ContainerInstanceManagementClient instance
277
resource_group_name (str): Resource group name
278
container_group_name (str): Container group name
279
virtual_network_name (str): Virtual network name
280
subnet_name (str): Subnet name
281
282
Returns:
283
dict: Troubleshooting information
284
"""
285
286
troubleshooting_info = {
287
'container_group_status': {},
288
'network_dependencies': [],
289
'recommendations': []
290
}
291
292
try:
293
# Check container group status
294
container_group = client.container_groups.get(
295
resource_group_name=resource_group_name,
296
container_group_name=container_group_name
297
)
298
299
troubleshooting_info['container_group_status'] = {
300
'name': container_group.name,
301
'provisioning_state': container_group.provisioning_state,
302
'has_ip_address': container_group.ip_address is not None,
303
'ip_type': container_group.ip_address.type if container_group.ip_address else None,
304
'subnet_ids': [subnet.id for subnet in container_group.subnet_ids] if container_group.subnet_ids else []
305
}
306
307
# Check network dependencies
308
try:
309
dependencies = client.container_groups.get_outbound_network_dependencies_endpoints(
310
resource_group_name=resource_group_name,
311
container_group_name=container_group_name
312
)
313
troubleshooting_info['network_dependencies'] = dependencies
314
except Exception as e:
315
troubleshooting_info['network_dependencies'] = f"Error retrieving dependencies: {e}"
316
317
# Generate recommendations
318
recommendations = []
319
320
if container_group.provisioning_state != "Succeeded":
321
recommendations.append(f"Container group is in '{container_group.provisioning_state}' state. Check deployment logs.")
322
323
if not container_group.ip_address:
324
recommendations.append("Container group has no IP address configured. Check networking configuration.")
325
elif container_group.ip_address.type == "Private" and not container_group.subnet_ids:
326
recommendations.append("Private IP configured but no subnet specified. Verify virtual network integration.")
327
328
if container_group.subnet_ids:
329
recommendations.append("Container group is using virtual network integration. Consider cleaning up subnet service association links if removing the container group.")
330
331
troubleshooting_info['recommendations'] = recommendations
332
333
except Exception as e:
334
troubleshooting_info['error'] = f"Failed to retrieve container group information: {e}"
335
336
return troubleshooting_info
337
338
# Usage
339
troubleshooting_results = troubleshoot_network_integration(
340
client=client,
341
resource_group_name="production-rg",
342
container_group_name="web-app-cg",
343
virtual_network_name="production-vnet",
344
subnet_name="container-subnet"
345
)
346
347
print("=== Network Integration Troubleshooting ===")
348
if 'error' in troubleshooting_results:
349
print(f"❌ Error: {troubleshooting_results['error']}")
350
else:
351
cg_status = troubleshooting_results['container_group_status']
352
print(f"Container Group: {cg_status['name']}")
353
print(f"Provisioning State: {cg_status['provisioning_state']}")
354
print(f"Has IP Address: {cg_status['has_ip_address']}")
355
if cg_status['has_ip_address']:
356
print(f"IP Type: {cg_status['ip_type']}")
357
358
if cg_status['subnet_ids']:
359
print("Subnet IDs:")
360
for subnet_id in cg_status['subnet_ids']:
361
print(f" - {subnet_id}")
362
363
if troubleshooting_results['network_dependencies']:
364
print("Network Dependencies:")
365
if isinstance(troubleshooting_results['network_dependencies'], list):
366
for dep in troubleshooting_results['network_dependencies']:
367
print(f" - {dep}")
368
else:
369
print(f" {troubleshooting_results['network_dependencies']}")
370
371
if troubleshooting_results['recommendations']:
372
print("Recommendations:")
373
for rec in troubleshooting_results['recommendations']:
374
print(f" 💡 {rec}")
375
```
376
377
## Important Notes
378
379
- Subnet service association links are automatically created when container groups are deployed to virtual network subnets
380
- These links must be cleaned up manually when container groups are deleted to avoid orphaned network resources
381
- The service association link name typically follows the pattern `{container-group-name}-link` but may vary
382
- Deleting a service association link is a long-running operation and should be monitored for completion
383
- Network cleanup should only be performed after confirming that container groups have been successfully deleted