Microsoft Azure Monitor Client Library for Python
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Automated resource scaling based on metrics, schedules, and predictive policies. Manages autoscale settings that automatically adjust resource capacity to meet demand while optimizing costs and performance.
Create, update, and manage autoscale settings with support for metric-based and schedule-based scaling rules.
def create_or_update(resource_group_name: str, autoscale_setting_name: str, parameters: AutoscaleSettingResource, **kwargs: Any) -> AutoscaleSettingResource:
"""
Creates or updates an autoscale setting.
Parameters:
- resource_group_name: str - Name of the resource group
- autoscale_setting_name: str - Name of the autoscale setting
- parameters: AutoscaleSettingResource - Autoscale configuration
Returns:
AutoscaleSettingResource - The created or updated autoscale setting
"""
def get(resource_group_name: str, autoscale_setting_name: str, **kwargs: Any) -> AutoscaleSettingResource:
"""
Gets an autoscale setting.
Parameters:
- resource_group_name: str - Name of the resource group
- autoscale_setting_name: str - Name of the autoscale setting
Returns:
AutoscaleSettingResource - The autoscale setting details
"""
def delete(resource_group_name: str, autoscale_setting_name: str, **kwargs: Any) -> None:
"""
Deletes an autoscale setting.
Parameters:
- resource_group_name: str - Name of the resource group
- autoscale_setting_name: str - Name of the autoscale setting
"""
def update(resource_group_name: str, autoscale_setting_name: str, autoscale_setting_resource: AutoscaleSettingResourcePatch, **kwargs: Any) -> AutoscaleSettingResource:
"""
Updates an autoscale setting.
Parameters:
- resource_group_name: str - Name of the resource group
- autoscale_setting_name: str - Name of the autoscale setting
- autoscale_setting_resource: AutoscaleSettingResourcePatch - Properties to update
Returns:
AutoscaleSettingResource - The updated autoscale setting
"""List autoscale settings within subscriptions and resource groups.
def list_by_subscription(**kwargs: Any) -> ItemPaged[AutoscaleSettingResource]:
"""
Lists the autoscale settings for a subscription.
Returns:
ItemPaged[AutoscaleSettingResource] - Paginated list of autoscale settings
"""
def list_by_resource_group(resource_group_name: str, **kwargs: Any) -> ItemPaged[AutoscaleSettingResource]:
"""
Lists the autoscale settings for a resource group.
Parameters:
- resource_group_name: str - Name of the resource group
Returns:
ItemPaged[AutoscaleSettingResource] - Paginated list of autoscale settings
"""Access predictive autoscale metric data for forecast-based scaling decisions.
def get(resource_group_name: str, autoscale_setting_name: str, timespan: str, interval: str, metricnamespace: str, metricname: str, aggregation: str, **kwargs: Any) -> PredictiveResponse:
"""
Get predictive autoscale metric future data.
Parameters:
- resource_group_name: str - Name of the resource group
- autoscale_setting_name: str - Name of the autoscale setting
- timespan: str - Time range for prediction (ISO 8601)
- interval: str - Prediction interval (ISO 8601)
- metricnamespace: str - Metric namespace
- metricname: str - Metric name
- aggregation: str - Aggregation type
Returns:
PredictiveResponse - Predictive metric data
"""from azure.mgmt.monitor.models import (
AutoscaleSettingResource, AutoscaleProfile, ScaleRule,
MetricTrigger, ScaleAction, ScaleCapacity, TimeWindow
)
# Define metric trigger for scale out
scale_out_trigger = MetricTrigger(
metric_name="Percentage CPU",
metric_namespace="Microsoft.Compute/virtualMachineScaleSets",
metric_resource_uri=f"/subscriptions/{subscription_id}/resourceGroups/web-rg/providers/Microsoft.Compute/virtualMachineScaleSets/web-vmss",
time_grain="PT1M",
statistic="Average",
time_window="PT5M",
time_aggregation="Average",
operator="GreaterThan",
threshold=75.0
)
# Define scale out action
scale_out_action = ScaleAction(
direction="Increase",
type="ChangeCount",
value="1",
cooldown="PT5M" # 5-minute cooldown
)
# Define scale in rule
scale_in_trigger = MetricTrigger(
metric_name="Percentage CPU",
metric_namespace="Microsoft.Compute/virtualMachineScaleSets",
metric_resource_uri=f"/subscriptions/{subscription_id}/resourceGroups/web-rg/providers/Microsoft.Compute/virtualMachineScaleSets/web-vmss",
time_grain="PT1M",
statistic="Average",
time_window="PT5M",
time_aggregation="Average",
operator="LessThan",
threshold=25.0
)
scale_in_action = ScaleAction(
direction="Decrease",
type="ChangeCount",
value="1",
cooldown="PT5M"
)
# Create scale rules
rules = [
ScaleRule(metric_trigger=scale_out_trigger, scale_action=scale_out_action),
ScaleRule(metric_trigger=scale_in_trigger, scale_action=scale_in_action)
]
# Define capacity limits
capacity = ScaleCapacity(
minimum="2", # Minimum 2 instances
maximum="10", # Maximum 10 instances
default="2" # Default 2 instances
)
# Create autoscale profile
profile = AutoscaleProfile(
name="Default",
capacity=capacity,
rules=rules
)
# Create autoscale setting
autoscale_setting = AutoscaleSettingResource(
location="East US",
profiles=[profile],
enabled=True,
target_resource_uri=f"/subscriptions/{subscription_id}/resourceGroups/web-rg/providers/Microsoft.Compute/virtualMachineScaleSets/web-vmss",
target_resource_location="East US"
)
result = client.autoscale_settings.create_or_update(
resource_group_name="web-rg",
autoscale_setting_name="web-vmss-autoscale",
parameters=autoscale_setting
)from azure.mgmt.monitor.models import (
Recurrence, RecurrentSchedule, RecurrenceFrequency
)
# Create schedule for business hours (scale up)
business_hours_schedule = RecurrentSchedule(
time_zone="Pacific Standard Time",
days=["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"],
hours=[8], # 8 AM
minutes=[0]
)
business_hours_recurrence = Recurrence(
frequency=RecurrenceFrequency.WEEK,
schedule=business_hours_schedule
)
# Business hours profile (higher capacity)
business_profile = AutoscaleProfile(
name="BusinessHours",
capacity=ScaleCapacity(minimum="5", maximum="20", default="10"),
rules=[], # No metric rules, just scheduled scaling
recurrence=business_hours_recurrence
)
# Create schedule for off hours (scale down)
off_hours_schedule = RecurrentSchedule(
time_zone="Pacific Standard Time",
days=["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"],
hours=[18], # 6 PM
minutes=[0]
)
off_hours_recurrence = Recurrence(
frequency=RecurrenceFrequency.WEEK,
schedule=off_hours_schedule
)
# Off hours profile (lower capacity)
off_hours_profile = AutoscaleProfile(
name="OffHours",
capacity=ScaleCapacity(minimum="2", maximum="5", default="2"),
rules=[],
recurrence=off_hours_recurrence
)from azure.mgmt.monitor.models import PredictiveAutoscalePolicy
# Enable predictive autoscaling
predictive_policy = PredictiveAutoscalePolicy(
scale_mode="Enabled", # Enable predictive scaling
scale_look_ahead_time="PT30M" # Look ahead 30 minutes
)
# Add predictive policy to profile
profile_with_prediction = AutoscaleProfile(
name="PredictiveProfile",
capacity=capacity,
rules=rules,
predictive_autoscale_policy=predictive_policy
)
# Get predictive metrics
predictive_data = client.predictive_metric.get(
resource_group_name="web-rg",
autoscale_setting_name="web-vmss-autoscale",
timespan="2024-01-01T00:00:00Z/2024-01-01T12:00:00Z",
interval="PT5M",
metricnamespace="Microsoft.Compute/virtualMachineScaleSets",
metricname="Percentage CPU",
aggregation="Average"
)
print(f"Predicted values: {predictive_data.data}")class AutoscaleSettingResource:
"""Autoscale setting resource."""
location: str # Resource location
profiles: List[AutoscaleProfile] # Autoscale profiles
enabled: Optional[bool] # Whether autoscaling is enabled
target_resource_uri: Optional[str] # Target resource to scale
target_resource_location: Optional[str] # Target resource location
notifications: Optional[List[AutoscaleNotification]] # Notifications
class AutoscaleProfile:
"""Autoscale profile with scaling rules."""
name: str # Profile name
capacity: ScaleCapacity # Scaling capacity limits
rules: List[ScaleRule] # Scaling rules
fixed_date: Optional[TimeWindow] # Fixed date profile
recurrence: Optional[Recurrence] # Recurring schedule
predictive_autoscale_policy: Optional[PredictiveAutoscalePolicy] # Predictive scaling
class ScaleCapacity:
"""Scaling capacity configuration."""
minimum: str # Minimum instance count
maximum: str # Maximum instance count
default: str # Default instance count
class ScaleRule:
"""Autoscale rule definition."""
metric_trigger: MetricTrigger # Metric that triggers scaling
scale_action: ScaleAction # Action to take when triggered
class MetricTrigger:
"""Metric trigger for autoscaling."""
metric_name: str # Metric name
metric_namespace: str # Metric namespace
metric_resource_uri: str # Resource to monitor
time_grain: str # Metric collection frequency
statistic: MetricStatisticType # Statistic calculation method
time_window: str # Time window for evaluation
time_aggregation: TimeAggregationType # Time aggregation method
operator: ComparisonOperationType # Comparison operator
threshold: float # Threshold value
dimensions: Optional[List[ScaleRuleMetricDimension]] # Metric dimensions
divide_per_instance: Optional[bool] # Divide by instance count
class ScaleAction:
"""Action to perform when scaling."""
direction: ScaleDirection # Scale direction (Increase/Decrease)
type: ScaleType # Scale type (ChangeCount/PercentChangeCount/ExactCount)
value: str # Scale amount
cooldown: str # Cooldown period after scaling
class AutoscaleNotification:
"""Notification configuration."""
operation: str # Operation type
email: Optional[EmailNotification] # Email notification settings
webhooks: Optional[List[WebhookNotification]] # Webhook notifications
class PredictiveResponse:
"""Predictive autoscale response."""
timespan: Optional[str] # Time range
interval: Optional[str] # Prediction interval
metric_name: Optional[str] # Metric name
target_resource_id: Optional[str] # Target resource
data: Optional[List[PredictiveValue]] # Predicted values
class PredictiveValue:
"""Predicted metric value."""
time_stamp: Optional[datetime] # Prediction timestamp
value: Optional[float] # Predicted value
class PredictiveAutoscalePolicy:
"""Predictive autoscale configuration."""
scale_mode: PredictiveAutoscalePolicyScaleMode # Prediction mode
scale_look_ahead_time: Optional[str] # Look-ahead time
ScaleDirection = Union["None", "Increase", "Decrease"]
ScaleType = Union["ChangeCount", "PercentChangeCount", "ExactCount"]
MetricStatisticType = Union["Average", "Min", "Max", "Sum", "Count"]
TimeAggregationType = Union["Average", "Minimum", "Maximum", "Total", "Count", "Last"]
PredictiveAutoscalePolicyScaleMode = Union["Disabled", "ForecastOnly", "Enabled"]Install with Tessl CLI
npx tessl i tessl/pypi-azure-mgmt-monitor