CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-azure-mgmt-core

Azure management core library defines extensions to Azure Core that are specific to ARM (Azure Resource Management) needed when you use client libraries

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

resource-tools.mddocs/

Resource Tools

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.

Capabilities

Resource ID Parsing

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]
    """

Usage Example

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.

Resource ID Construction

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
    """

Usage Example

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/myext

Resource ID Validation

Validates 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
    """

Usage Example

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!")

Resource Name Validation

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
    """

ARM Naming Rules

Resource names must:

  • Be 1-260 characters long
  • Not contain: < > % & : \ ? /
  • Follow pattern: ^[^<>%&:\\?/]{1,260}$

Usage Example

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!")

ARM Endpoints

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]
    """

Supported Cloud Settings

  • AZURE_PUBLIC_CLOUD: Global Azure (management.azure.com)
  • AZURE_CHINA_CLOUD: Azure China (management.chinacloudapi.cn)
  • AZURE_US_GOVERNMENT: Azure US Government (management.usgovcloudapi.net)

Usage Example

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"]
# }

Key Features

Hierarchical Resource Support

The parsing and construction functions support complex Azure resource hierarchies:

  • Root resources: /subscriptions/{sub}/resourceGroups/{rg}/providers/{ns}/{type}/{name}
  • Child resources: .../{child_type_1}/{child_name_1}
  • Multi-level nesting: .../{child_type_1}/{child_name_1}/{child_type_2}/{child_name_2}

Robust Error Handling

  • Invalid resource IDs return minimal info instead of throwing exceptions
  • Validation functions can optionally throw custom exceptions
  • Missing required parameters gracefully truncate resource ID construction

ARM Compliance

All functions follow official ARM specifications:

  • Resource ID format compliance
  • Naming convention validation
  • Cloud-specific endpoint handling

Performance Optimized

Uses compiled regular expressions for efficient parsing:

  • Resource ID pattern matching
  • Child resource extraction
  • Name validation

Regular Expression Patterns

# 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

docs

exceptions.md

index.md

pipeline-clients.md

policies.md

polling.md

resource-tools.md

tile.json