0
# Resource Tools
1
2
Utilities for parsing Azure resource identifiers, constructing resource IDs, and validating resource names according to ARM specifications. These tools handle the complex structure of Azure resource identifiers and provide validation for ARM naming conventions.
3
4
## Capabilities
5
6
### Resource ID Parsing
7
8
Parses Azure resource identifiers into their component parts, handling complex hierarchical resource structures with child resources and multiple levels of nesting.
9
10
```python { .api }
11
def parse_resource_id(rid: str) -> Mapping[str, Union[str, int]]:
12
"""Parses a resource_id into its various parts.
13
14
Returns a dictionary with a single key-value pair, 'name': rid, if invalid resource id.
15
16
:param rid: The resource id being parsed
17
:type rid: str
18
:returns: A dictionary with with following key/value pairs (if found):
19
20
- subscription: Subscription id
21
- resource_group: Name of resource group
22
- namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
23
- type: Type of the root resource (i.e. virtualMachines)
24
- name: Name of the root resource
25
- child_namespace_{level}: Namespace for the child resource of that level
26
- child_type_{level}: Type of the child resource of that level
27
- child_name_{level}: Name of the child resource of that level
28
- last_child_num: Level of the last child
29
- resource_parent: Computed parent in the following pattern: providers/{namespace}/{parent}/{type}/{name}
30
- resource_namespace: Same as namespace. Note that this may be different than the target resource's namespace.
31
- resource_type: Type of the target resource (not the parent)
32
- resource_name: Name of the target resource (not the parent)
33
34
:rtype: dict[str,str]
35
"""
36
```
37
38
#### Usage Example
39
40
```python
41
from azure.mgmt.core.tools import parse_resource_id
42
43
# Parse a simple resource ID
44
resource_id = "/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/mygroup/providers/Microsoft.Compute/virtualMachines/myvm"
45
46
parsed = parse_resource_id(resource_id)
47
print(parsed)
48
# Output:
49
# {
50
# 'subscription': '12345678-1234-1234-1234-123456789012',
51
# 'resource_group': 'mygroup',
52
# 'namespace': 'Microsoft.Compute',
53
# 'type': 'virtualMachines',
54
# 'name': 'myvm',
55
# 'resource_namespace': 'Microsoft.Compute',
56
# 'resource_type': 'virtualMachines',
57
# 'resource_name': 'myvm'
58
# }
59
60
# Parse a nested resource ID with child resources
61
nested_id = "/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/mygroup/providers/Microsoft.Compute/virtualMachines/myvm/extensions/myext"
62
63
parsed_nested = parse_resource_id(nested_id)
64
print(parsed_nested)
65
# Output includes child_type_1, child_name_1, last_child_num, etc.
66
```
67
68
### Resource ID Construction
69
70
Creates valid Azure resource identifiers from component parts, supporting complex hierarchical structures with multiple levels of child resources.
71
72
```python { .api }
73
def resource_id(**kwargs: Optional[str]) -> str:
74
"""Create a valid resource id string from the given parts.
75
76
This method builds the resource id from the left until the next required id parameter
77
to be appended is not found. It then returns the built up id.
78
79
:keyword str subscription: (required) Subscription id
80
:keyword str resource_group: Name of resource group
81
:keyword str namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
82
:keyword str type: Type of the resource (i.e. virtualMachines)
83
:keyword str name: Name of the resource (or parent if child_name is also specified)
84
:keyword str child_namespace_{level}: Namespace for the child resource of that level (optional)
85
:keyword str child_type_{level}: Type of the child resource of that level
86
:keyword str child_name_{level}: Name of the child resource of that level
87
88
:returns: A resource id built from the given arguments.
89
:rtype: str
90
"""
91
```
92
93
#### Usage Example
94
95
```python
96
from azure.mgmt.core.tools import resource_id
97
98
# Create a simple resource ID
99
simple_id = resource_id(
100
subscription="12345678-1234-1234-1234-123456789012",
101
resource_group="mygroup",
102
namespace="Microsoft.Compute",
103
type="virtualMachines",
104
name="myvm"
105
)
106
print(simple_id)
107
# Output: /subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/mygroup/providers/Microsoft.Compute/virtualMachines/myvm
108
109
# Create a nested resource ID
110
nested_id = resource_id(
111
subscription="12345678-1234-1234-1234-123456789012",
112
resource_group="mygroup",
113
namespace="Microsoft.Compute",
114
type="virtualMachines",
115
name="myvm",
116
child_type_1="extensions",
117
child_name_1="myext"
118
)
119
print(nested_id)
120
# Output: /subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/mygroup/providers/Microsoft.Compute/virtualMachines/myvm/extensions/myext
121
```
122
123
### Resource ID Validation
124
125
Validates Azure resource identifiers to ensure they conform to ARM specifications and can be successfully parsed.
126
127
```python { .api }
128
def is_valid_resource_id(rid: str, exception_type: Optional[Type[BaseException]] = None) -> bool:
129
"""Validates the given resource id.
130
131
:param rid: The resource id being validated.
132
:type rid: str
133
:param exception_type: Raises this Exception if invalid.
134
:type exception_type: Exception
135
:returns: A boolean describing whether the id is valid.
136
:rtype: bool
137
"""
138
```
139
140
#### Usage Example
141
142
```python
143
from azure.mgmt.core.tools import is_valid_resource_id
144
145
# Validate a resource ID
146
valid_id = "/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/mygroup/providers/Microsoft.Compute/virtualMachines/myvm"
147
invalid_id = "not-a-resource-id"
148
149
print(is_valid_resource_id(valid_id)) # True
150
print(is_valid_resource_id(invalid_id)) # False
151
152
# Validate with exception throwing
153
try:
154
is_valid_resource_id(invalid_id, ValueError)
155
except ValueError:
156
print("Invalid resource ID!")
157
```
158
159
### Resource Name Validation
160
161
Validates resource names according to ARM naming guidelines. Individual Azure services may have more restrictive naming requirements.
162
163
```python { .api }
164
def is_valid_resource_name(rname: str, exception_type: Optional[Type[BaseException]] = None) -> bool:
165
"""Validates the given resource name to ARM guidelines, individual services may be more restrictive.
166
167
:param rname: The resource name being validated.
168
:type rname: str
169
:param exception_type: Raises this Exception if invalid.
170
:type exception_type: Exception
171
:returns: A boolean describing whether the name is valid.
172
:rtype: bool
173
"""
174
```
175
176
#### ARM Naming Rules
177
178
Resource names must:
179
- Be 1-260 characters long
180
- Not contain: `< > % & : \ ? /`
181
- Follow pattern: `^[^<>%&:\\?/]{1,260}$`
182
183
#### Usage Example
184
185
```python
186
from azure.mgmt.core.tools import is_valid_resource_name
187
188
# Valid names
189
print(is_valid_resource_name("myvm")) # True
190
print(is_valid_resource_name("my-vm-123")) # True
191
192
# Invalid names
193
print(is_valid_resource_name("my/vm")) # False (contains /)
194
print(is_valid_resource_name("my:vm")) # False (contains :)
195
print(is_valid_resource_name("")) # False (empty)
196
197
# Validate with exception throwing
198
try:
199
is_valid_resource_name("my/vm", ValueError)
200
except ValueError:
201
print("Invalid resource name!")
202
```
203
204
### ARM Endpoints
205
206
Retrieves ARM endpoint URLs and credential scopes for different Azure cloud environments.
207
208
```python { .api }
209
def get_arm_endpoints(cloud_setting: AzureClouds) -> Dict[str, Any]:
210
"""Get the ARM endpoint and ARM credential scopes for the given cloud setting.
211
212
:param cloud_setting: The cloud setting for which to get the ARM endpoint.
213
:type cloud_setting: AzureClouds
214
:return: The ARM endpoint and ARM credential scopes.
215
:rtype: dict[str, Any]
216
"""
217
```
218
219
#### Supported Cloud Settings
220
221
- **AZURE_PUBLIC_CLOUD**: Global Azure (management.azure.com)
222
- **AZURE_CHINA_CLOUD**: Azure China (management.chinacloudapi.cn)
223
- **AZURE_US_GOVERNMENT**: Azure US Government (management.usgovcloudapi.net)
224
225
#### Usage Example
226
227
```python
228
from azure.mgmt.core.tools import get_arm_endpoints
229
from azure.core import AzureClouds
230
231
# Get endpoints for public cloud
232
public_endpoints = get_arm_endpoints(AzureClouds.AZURE_PUBLIC_CLOUD)
233
print(public_endpoints)
234
# Output:
235
# {
236
# "resource_manager": "https://management.azure.com/",
237
# "credential_scopes": ["https://management.azure.com/.default"]
238
# }
239
240
# Get endpoints for China cloud
241
china_endpoints = get_arm_endpoints(AzureClouds.AZURE_CHINA_CLOUD)
242
print(china_endpoints)
243
# Output:
244
# {
245
# "resource_manager": "https://management.chinacloudapi.cn/",
246
# "credential_scopes": ["https://management.chinacloudapi.cn/.default"]
247
# }
248
249
# Get endpoints for US Government cloud
250
gov_endpoints = get_arm_endpoints(AzureClouds.AZURE_US_GOVERNMENT)
251
print(gov_endpoints)
252
# Output:
253
# {
254
# "resource_manager": "https://management.usgovcloudapi.net/",
255
# "credential_scopes": ["https://management.core.usgovcloudapi.net/.default"]
256
# }
257
```
258
259
## Key Features
260
261
### Hierarchical Resource Support
262
263
The parsing and construction functions support complex Azure resource hierarchies:
264
- Root resources: `/subscriptions/{sub}/resourceGroups/{rg}/providers/{ns}/{type}/{name}`
265
- Child resources: `.../{child_type_1}/{child_name_1}`
266
- Multi-level nesting: `.../{child_type_1}/{child_name_1}/{child_type_2}/{child_name_2}`
267
268
### Robust Error Handling
269
270
- Invalid resource IDs return minimal info instead of throwing exceptions
271
- Validation functions can optionally throw custom exceptions
272
- Missing required parameters gracefully truncate resource ID construction
273
274
### ARM Compliance
275
276
All functions follow official ARM specifications:
277
- Resource ID format compliance
278
- Naming convention validation
279
- Cloud-specific endpoint handling
280
281
### Performance Optimized
282
283
Uses compiled regular expressions for efficient parsing:
284
- Resource ID pattern matching
285
- Child resource extraction
286
- Name validation
287
288
## Regular Expression Patterns
289
290
```python { .api }
291
# Internal patterns used by the tools
292
_ARMID_RE = re.compile(
293
"(?i)/subscriptions/(?P<subscription>[^/]+)(/resourceGroups/(?P<resource_group>[^/]+))?"
294
+ "(/providers/(?P<namespace>[^/]+)/(?P<type>[^/]*)/(?P<name>[^/]+)(?P<children>.*))?"
295
)
296
297
_CHILDREN_RE = re.compile(
298
"(?i)(/providers/(?P<child_namespace>[^/]+))?/"
299
+ "(?P<child_type>[^/]*)/(?P<child_name>[^/]+)"
300
)
301
302
_ARMNAME_RE = re.compile("^[^<>%&:\\?/]{1,260}$")
303
```