Azure management core library defines extensions to Azure Core that are specific to ARM (Azure Resource Management) needed when you use client libraries
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
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.
Parses Azure resource identifiers into their component parts, handling complex hierarchical resource structures with child resources and multiple levels of nesting.
def parse_resource_id(rid: str) -> Mapping[str, Union[str, int]]:
"""Parses a resource_id into its various parts.
Returns a dictionary with a single key-value pair, 'name': rid, if invalid resource id.
:param rid: The resource id being parsed
:type rid: str
:returns: A dictionary with with following key/value pairs (if found):
- subscription: Subscription id
- resource_group: Name of resource group
- namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
- type: Type of the root resource (i.e. virtualMachines)
- name: Name of the root resource
- child_namespace_{level}: Namespace for the child resource of that level
- child_type_{level}: Type of the child resource of that level
- child_name_{level}: Name of the child resource of that level
- last_child_num: Level of the last child
- resource_parent: Computed parent in the following pattern: providers/{namespace}/{parent}/{type}/{name}
- resource_namespace: Same as namespace. Note that this may be different than the target resource's namespace.
- resource_type: Type of the target resource (not the parent)
- resource_name: Name of the target resource (not the parent)
:rtype: dict[str,str]
"""from azure.mgmt.core.tools import parse_resource_id
# Parse a simple resource ID
resource_id = "/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/mygroup/providers/Microsoft.Compute/virtualMachines/myvm"
parsed = parse_resource_id(resource_id)
print(parsed)
# Output:
# {
# 'subscription': '12345678-1234-1234-1234-123456789012',
# 'resource_group': 'mygroup',
# 'namespace': 'Microsoft.Compute',
# 'type': 'virtualMachines',
# 'name': 'myvm',
# 'resource_namespace': 'Microsoft.Compute',
# 'resource_type': 'virtualMachines',
# 'resource_name': 'myvm'
# }
# Parse a nested resource ID with child resources
nested_id = "/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/mygroup/providers/Microsoft.Compute/virtualMachines/myvm/extensions/myext"
parsed_nested = parse_resource_id(nested_id)
print(parsed_nested)
# Output includes child_type_1, child_name_1, last_child_num, etc.Creates valid Azure resource identifiers from component parts, supporting complex hierarchical structures with multiple levels of child resources.
def resource_id(**kwargs: Optional[str]) -> str:
"""Create a valid resource id string from the given parts.
This method builds the resource id from the left until the next required id parameter
to be appended is not found. It then returns the built up id.
:keyword str subscription: (required) Subscription id
:keyword str resource_group: Name of resource group
:keyword str namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
:keyword str type: Type of the resource (i.e. virtualMachines)
:keyword str name: Name of the resource (or parent if child_name is also specified)
:keyword str child_namespace_{level}: Namespace for the child resource of that level (optional)
:keyword str child_type_{level}: Type of the child resource of that level
:keyword str child_name_{level}: Name of the child resource of that level
:returns: A resource id built from the given arguments.
:rtype: str
"""from azure.mgmt.core.tools import resource_id
# Create a simple resource ID
simple_id = resource_id(
subscription="12345678-1234-1234-1234-123456789012",
resource_group="mygroup",
namespace="Microsoft.Compute",
type="virtualMachines",
name="myvm"
)
print(simple_id)
# Output: /subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/mygroup/providers/Microsoft.Compute/virtualMachines/myvm
# Create a nested resource ID
nested_id = resource_id(
subscription="12345678-1234-1234-1234-123456789012",
resource_group="mygroup",
namespace="Microsoft.Compute",
type="virtualMachines",
name="myvm",
child_type_1="extensions",
child_name_1="myext"
)
print(nested_id)
# Output: /subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/mygroup/providers/Microsoft.Compute/virtualMachines/myvm/extensions/myextValidates Azure resource identifiers to ensure they conform to ARM specifications and can be successfully parsed.
def is_valid_resource_id(rid: str, exception_type: Optional[Type[BaseException]] = None) -> bool:
"""Validates the given resource id.
:param rid: The resource id being validated.
:type rid: str
:param exception_type: Raises this Exception if invalid.
:type exception_type: Exception
:returns: A boolean describing whether the id is valid.
:rtype: bool
"""from azure.mgmt.core.tools import is_valid_resource_id
# Validate a resource ID
valid_id = "/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/mygroup/providers/Microsoft.Compute/virtualMachines/myvm"
invalid_id = "not-a-resource-id"
print(is_valid_resource_id(valid_id)) # True
print(is_valid_resource_id(invalid_id)) # False
# Validate with exception throwing
try:
is_valid_resource_id(invalid_id, ValueError)
except ValueError:
print("Invalid resource ID!")Validates resource names according to ARM naming guidelines. Individual Azure services may have more restrictive naming requirements.
def is_valid_resource_name(rname: str, exception_type: Optional[Type[BaseException]] = None) -> bool:
"""Validates the given resource name to ARM guidelines, individual services may be more restrictive.
:param rname: The resource name being validated.
:type rname: str
:param exception_type: Raises this Exception if invalid.
:type exception_type: Exception
:returns: A boolean describing whether the name is valid.
:rtype: bool
"""Resource names must:
< > % & : \ ? /^[^<>%&:\\?/]{1,260}$from azure.mgmt.core.tools import is_valid_resource_name
# Valid names
print(is_valid_resource_name("myvm")) # True
print(is_valid_resource_name("my-vm-123")) # True
# Invalid names
print(is_valid_resource_name("my/vm")) # False (contains /)
print(is_valid_resource_name("my:vm")) # False (contains :)
print(is_valid_resource_name("")) # False (empty)
# Validate with exception throwing
try:
is_valid_resource_name("my/vm", ValueError)
except ValueError:
print("Invalid resource name!")Retrieves ARM endpoint URLs and credential scopes for different Azure cloud environments.
def get_arm_endpoints(cloud_setting: AzureClouds) -> Dict[str, Any]:
"""Get the ARM endpoint and ARM credential scopes for the given cloud setting.
:param cloud_setting: The cloud setting for which to get the ARM endpoint.
:type cloud_setting: AzureClouds
:return: The ARM endpoint and ARM credential scopes.
:rtype: dict[str, Any]
"""from azure.mgmt.core.tools import get_arm_endpoints
from azure.core import AzureClouds
# Get endpoints for public cloud
public_endpoints = get_arm_endpoints(AzureClouds.AZURE_PUBLIC_CLOUD)
print(public_endpoints)
# Output:
# {
# "resource_manager": "https://management.azure.com/",
# "credential_scopes": ["https://management.azure.com/.default"]
# }
# Get endpoints for China cloud
china_endpoints = get_arm_endpoints(AzureClouds.AZURE_CHINA_CLOUD)
print(china_endpoints)
# Output:
# {
# "resource_manager": "https://management.chinacloudapi.cn/",
# "credential_scopes": ["https://management.chinacloudapi.cn/.default"]
# }
# Get endpoints for US Government cloud
gov_endpoints = get_arm_endpoints(AzureClouds.AZURE_US_GOVERNMENT)
print(gov_endpoints)
# Output:
# {
# "resource_manager": "https://management.usgovcloudapi.net/",
# "credential_scopes": ["https://management.core.usgovcloudapi.net/.default"]
# }The parsing and construction functions support complex Azure resource hierarchies:
/subscriptions/{sub}/resourceGroups/{rg}/providers/{ns}/{type}/{name}.../{child_type_1}/{child_name_1}.../{child_type_1}/{child_name_1}/{child_type_2}/{child_name_2}All functions follow official ARM specifications:
Uses compiled regular expressions for efficient parsing:
# Internal patterns used by the tools
_ARMID_RE = re.compile(
"(?i)/subscriptions/(?P<subscription>[^/]+)(/resourceGroups/(?P<resource_group>[^/]+))?"
+ "(/providers/(?P<namespace>[^/]+)/(?P<type>[^/]*)/(?P<name>[^/]+)(?P<children>.*))?"
)
_CHILDREN_RE = re.compile(
"(?i)(/providers/(?P<child_namespace>[^/]+))?/"
+ "(?P<child_type>[^/]*)/(?P<child_name>[^/]+)"
)
_ARMNAME_RE = re.compile("^[^<>%&:\\?/]{1,260}$")Install with Tessl CLI
npx tessl i tessl/pypi-azure-mgmt-core