CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-azure-mgmt-subscription

Microsoft Azure Subscription Management Client Library for Python

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

service-operations.mddocs/

Service Operations

Service metadata and discovery operations that provide information about available API operations and service capabilities. These operations enable applications to discover and understand the full capabilities of the Azure Subscription Management service.

Capabilities

List Available API Operations

Lists all available Microsoft.Subscription API operations, providing metadata about each operation including names, descriptions, and capabilities.

def list(**kwargs) -> Iterable[Operation]:
    """
    Lists all of the available Microsoft.Subscription API operations.
    
    Returns:
        Iterable[Operation]: Paginated list of available API operations
    """

Usage Example:

from azure.identity import DefaultAzureCredential
from azure.mgmt.subscription import SubscriptionClient

credential = DefaultAzureCredential()
client = SubscriptionClient(credential)

try:
    operations = list(client.operations.list())
    
    print(f"Found {len(operations)} available operations:")
    
    # Group operations by resource type
    operation_groups = {}
    
    for operation in operations:
        # Extract resource type from operation name
        parts = operation.name.split('/')
        if len(parts) >= 2:
            resource_type = parts[1]
            if resource_type not in operation_groups:
                operation_groups[resource_type] = []
            operation_groups[resource_type].append(operation)
    
    # Display operations by group
    for resource_type, ops in operation_groups.items():
        print(f"\n{resource_type.upper()} Operations:")
        for op in ops:
            display = op.display
            if display:
                print(f"  {op.name}")
                print(f"    Description: {display.description}")
                print(f"    Provider: {display.provider}")
                print(f"    Resource: {display.resource}")
                print(f"    Operation: {display.operation}")
                print(f"    Data Action: {op.is_data_action}")
                print("    ---")
            
except Exception as e:
    print(f"Failed to list operations: {e}")

Advanced Usage Patterns

Operation Discovery and Validation

def discover_subscription_capabilities(client):
    """Discover and categorize subscription management capabilities."""
    
    try:
        operations = list(client.operations.list())
        
        capabilities = {
            "subscription_management": [],
            "tenant_operations": [],
            "alias_operations": [],
            "policy_operations": [],
            "billing_operations": [],
            "other": []
        }
        
        for operation in operations:
            name_lower = operation.name.lower()
            
            if "subscription" in name_lower and ("read" in name_lower or "list" in name_lower):
                capabilities["subscription_management"].append(operation)
            elif "tenant" in name_lower:
                capabilities["tenant_operations"].append(operation)
            elif "alias" in name_lower:
                capabilities["alias_operations"].append(operation)
            elif "policy" in name_lower or "policies" in name_lower:
                capabilities["policy_operations"].append(operation)
            elif "billing" in name_lower:
                capabilities["billing_operations"].append(operation)
            else:
                capabilities["other"].append(operation)
        
        # Display capabilities summary
        print("Azure Subscription Management Capabilities:")
        for category, ops in capabilities.items():
            if ops:
                print(f"\n{category.replace('_', ' ').title()}: {len(ops)} operations")
                for op in ops[:3]:  # Show first 3 operations as examples
                    if op.display:
                        print(f"  - {op.display.operation}: {op.display.description}")
                if len(ops) > 3:
                    print(f"  ... and {len(ops) - 3} more")
        
        return capabilities
        
    except Exception as e:
        print(f"Failed to discover capabilities: {e}")
        return {}

API Coverage Validation

def validate_api_coverage(client, expected_operations):
    """Validate that expected operations are available in the API."""
    
    try:
        available_operations = list(client.operations.list())
        available_names = {op.name for op in available_operations}
        
        validation_results = {}
        
        for expected_op in expected_operations:
            if expected_op in available_names:
                validation_results[expected_op] = "Available"
            else:
                validation_results[expected_op] = "Missing"
        
        # Find unexpected operations
        expected_set = set(expected_operations)
        unexpected = available_names - expected_set
        
        print("API Coverage Validation Results:")
        print(f"Expected Operations: {len(expected_operations)}")
        print(f"Available Operations: {len(available_operations)}")
        print(f"Missing Operations: {sum(1 for v in validation_results.values() if v == 'Missing')}")
        print(f"Unexpected Operations: {len(unexpected)}")
        
        # Show missing operations
        missing = [op for op, status in validation_results.items() if status == "Missing"]
        if missing:
            print("\nMissing Operations:")
            for op in missing:
                print(f"  - {op}")
        
        # Show some unexpected operations
        if unexpected:
            print(f"\nUnexpected Operations (showing first 5):")
            for op in list(unexpected)[:5]:
                print(f"  - {op}")
        
        return validation_results
        
    except Exception as e:
        print(f"Failed to validate API coverage: {e}")
        return {}

# Example usage
expected_ops = [
    "Microsoft.Subscription/subscriptions/read",
    "Microsoft.Subscription/subscriptions/locations/read",
    "Microsoft.Subscription/tenants/read",
    "Microsoft.Subscription/aliases/write",
    "Microsoft.Subscription/aliases/read",
    "Microsoft.Subscription/aliases/delete"
]

validation = validate_api_coverage(client, expected_ops)

Operation Metadata Analysis

def analyze_operation_metadata(client):
    """Analyze operation metadata for insights about the API."""
    
    try:
        operations = list(client.operations.list())
        
        analysis = {
            "total_operations": len(operations),
            "data_actions": 0,
            "management_actions": 0,
            "providers": set(),
            "resources": set(),
            "operation_types": {}
        }
        
        for operation in operations:
            # Count data vs management actions
            if operation.is_data_action:
                analysis["data_actions"] += 1
            else:
                analysis["management_actions"] += 1
            
            # Analyze display information
            if operation.display:
                display = operation.display
                analysis["providers"].add(display.provider)
                analysis["resources"].add(display.resource)
                
                # Categorize operation types
                op_type = display.operation.lower()
                if "read" in op_type or "list" in op_type or "get" in op_type:
                    category = "Read"
                elif "write" in op_type or "create" in op_type or "put" in op_type:
                    category = "Write"
                elif "delete" in op_type:
                    category = "Delete"
                else:
                    category = "Other"
                
                analysis["operation_types"][category] = analysis["operation_types"].get(category, 0) + 1
        
        # Display analysis
        print("Operation Metadata Analysis:")
        print(f"Total Operations: {analysis['total_operations']}")
        print(f"Data Actions: {analysis['data_actions']}")
        print(f"Management Actions: {analysis['management_actions']}")
        print(f"Unique Providers: {len(analysis['providers'])}")
        print(f"Unique Resources: {len(analysis['resources'])}")
        
        print("\nOperation Types:")
        for op_type, count in analysis["operation_types"].items():
            percentage = (count / analysis["total_operations"]) * 100
            print(f"  {op_type}: {count} ({percentage:.1f}%)")
        
        print("\nProviders:")
        for provider in sorted(analysis["providers"]):
            print(f"  - {provider}")
        
        print("\nResource Types:")
        for resource in sorted(analysis["resources"]):
            print(f"  - {resource}")
        
        return analysis
        
    except Exception as e:
        print(f"Failed to analyze operation metadata: {e}")
        return {}

Error Handling

from azure.core.exceptions import HttpResponseError

def handle_operations_errors(func, *args, **kwargs):
    """Error handler for operations listing."""
    try:
        return func(*args, **kwargs)
    except HttpResponseError as e:
        if e.status_code == 403:
            print("Insufficient permissions to list operations")
        elif e.status_code == 401:
            print("Authentication failed - check credentials")
        else:
            print(f"Error listing operations: {e.status_code} - {e.message}")
        raise
    except Exception as e:
        print(f"Unexpected error listing operations: {e}")
        raise

# Example usage
try:
    operations = handle_operations_errors(client.operations.list)
    operations_list = list(operations)
    print(f"Successfully retrieved {len(operations_list)} operations")
except Exception:
    print("Failed to retrieve operations list")

Integration with Other Capabilities

Dynamic Client Capability Detection

def detect_client_capabilities(client):
    """Detect what capabilities are available in the current client."""
    
    available_capabilities = {
        "subscription_management": False,
        "tenant_discovery": False,
        "subscription_lifecycle": False,
        "alias_management": False,
        "policy_management": False,
        "billing_account_access": False
    }
    
    try:
        operations = list(client.operations.list())
        
        for operation in operations:
            name = operation.name.lower()
            
            if "subscriptions/read" in name or "subscriptions/locations" in name:
                available_capabilities["subscription_management"] = True
            elif "tenants/read" in name:
                available_capabilities["tenant_discovery"] = True
            elif "subscriptions/cancel" in name or "subscriptions/rename" in name:
                available_capabilities["subscription_lifecycle"] = True
            elif "aliases" in name:
                available_capabilities["alias_management"] = True
            elif "policies" in name or "policy" in name:
                available_capabilities["policy_management"] = True
            elif "billingaccount" in name:
                available_capabilities["billing_account_access"] = True
        
        print("Detected Client Capabilities:")
        for capability, available in available_capabilities.items():
            status = "✓" if available else "✗"
            print(f"  {status} {capability.replace('_', ' ').title()}")
        
        return available_capabilities
        
    except Exception as e:
        print(f"Failed to detect capabilities: {e}")
        return available_capabilities

Types

class Operation:
    """Information about an API operation."""
    name: str  # Operation name (e.g., "Microsoft.Subscription/subscriptions/read")
    is_data_action: bool  # Whether this is a data action (vs management action)
    display: OperationDisplay  # Display information for the operation
    origin: str  # Origin of the operation
    action_type: str  # Type of action

class OperationDisplay:
    """Display information for an API operation."""
    provider: str  # Resource provider name (e.g., "Microsoft Subscription")
    resource: str  # Resource type (e.g., "Subscription")
    operation: str  # Operation name (e.g., "Get subscription")
    description: str  # Human-readable description of the operation

class OperationListResult:
    """Result of listing operations."""
    value: List[Operation]  # List of operations
    next_link: str  # URL for next page of results (optional)

Usage in Application Development

Service operations are particularly useful for:

  1. API Discovery: Understanding what operations are available
  2. Documentation Generation: Automatically generating API documentation
  3. Client Validation: Ensuring expected operations are available
  4. Feature Detection: Determining what capabilities are supported
  5. Monitoring: Tracking API changes and new features
  6. Testing: Validating API coverage in test suites

Install with Tessl CLI

npx tessl i tessl/pypi-azure-mgmt-subscription

docs

index.md

policy-management.md

service-operations.md

subscription-creation.md

subscription-lifecycle.md

subscription-management.md

tenant-operations.md

tile.json