| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
from __future__ import absolute_import, division, print_function |
| 8 |
__metaclass__ = type |
| 9 |
|
| 10 |
DOCUMENTATION = ''' |
| 11 |
--- |
| 12 |
module: azure_rm_monitorscheduledqueryrules |
| 13 |
version_added: "3.11.0" |
| 14 |
short_description: Create, update and delete Scheduled query rules |
| 15 |
description: |
| 16 |
- Create, update and delete Scheduled query rules |
| 17 |
|
| 18 |
options: |
| 19 |
name: |
| 20 |
description: |
| 21 |
- The name of the scheduled query rule you're creating/changing |
| 22 |
required: true |
| 23 |
type: str |
| 24 |
resource_group: |
| 25 |
description: |
| 26 |
- The name of the resource group |
| 27 |
required: true |
| 28 |
type: str |
| 29 |
location: |
| 30 |
description: |
| 31 |
- Location of the scheduled query rule |
| 32 |
- Scheduled query rules are usually reside at the location of your log analytics workspace. |
| 33 |
required: false |
| 34 |
type: str |
| 35 |
action: |
| 36 |
description: |
| 37 |
- The actions that will activate when the condition is met |
| 38 |
type: dict |
| 39 |
suboptions: |
| 40 |
azns_action: |
| 41 |
description: Azure action group reference |
| 42 |
type: dict |
| 43 |
suboptions: |
| 44 |
action_group: |
| 45 |
description: |
| 46 |
- The list of the Action Group IDs |
| 47 |
type: list |
| 48 |
elements: str |
| 49 |
email_subject: |
| 50 |
description: |
| 51 |
- Custom subject override for all email ids in Azure action group |
| 52 |
type: str |
| 53 |
odata_type: |
| 54 |
description: Specifies the action |
| 55 |
type: str |
| 56 |
choices: |
| 57 |
- AlertingAction |
| 58 |
- LogToMetricAction |
| 59 |
- >- |
| 60 |
Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.AlertingAction |
| 61 |
severity: |
| 62 |
description: Severity of the alert |
| 63 |
type: int |
| 64 |
choices: |
| 65 |
- 0 |
| 66 |
- 1 |
| 67 |
- 2 |
| 68 |
- 3 |
| 69 |
- 4 |
| 70 |
trigger: |
| 71 |
description: The trigger condition that results in the alert rule being. |
| 72 |
type: dict |
| 73 |
suboptions: |
| 74 |
metric_trigger: |
| 75 |
description: The trigger condition that results in the alert rule being. |
| 76 |
type: dict |
| 77 |
suboptions: |
| 78 |
metric_column: |
| 79 |
description: Evaluation of metric on a particular column. |
| 80 |
type: str |
| 81 |
metric_trigger_type: |
| 82 |
description: Metric Trigger Type. |
| 83 |
type: str |
| 84 |
choices: |
| 85 |
- Consecutive |
| 86 |
- Total |
| 87 |
threshold: |
| 88 |
description: The threshold of the metric trigger. |
| 89 |
type: float |
| 90 |
threshold_operator: |
| 91 |
description: Evaluation operation for Metric. |
| 92 |
type: str |
| 93 |
choices: |
| 94 |
- GreaterThanOrEqual |
| 95 |
- GreaterThan |
| 96 |
- LessThan |
| 97 |
- Equal |
| 98 |
threshold: |
| 99 |
description: Result or count threshold based on which rule should be triggered. |
| 100 |
type: float |
| 101 |
threshold_operator: |
| 102 |
description: Result or count threshold based on which rule should be triggered. |
| 103 |
type: str |
| 104 |
choices: |
| 105 |
- GreaterThanOrEqual |
| 106 |
- GreaterThan |
| 107 |
- LessThan |
| 108 |
source: |
| 109 |
description: Data Source against which rule will Query Data. |
| 110 |
type: dict |
| 111 |
suboptions: |
| 112 |
authorized_resources: |
| 113 |
description: List of Resource referred into query. |
| 114 |
type: list |
| 115 |
elements: str |
| 116 |
data_source_id: |
| 117 |
description: The resource uri over which log search query is to be run. |
| 118 |
type: str |
| 119 |
query: |
| 120 |
description: Log search query. Required for action type - AlertingAction. |
| 121 |
type: str |
| 122 |
query_type: |
| 123 |
description: Set value to 'ResultCount'. |
| 124 |
type: str |
| 125 |
choices: |
| 126 |
- ResultCount |
| 127 |
schedule: |
| 128 |
description: Schedule (Frequency, Time Window) for rule. Required for action type - AlertingAction. |
| 129 |
type: dict |
| 130 |
suboptions: |
| 131 |
frequency_in_minutes: |
| 132 |
description: Frequency (in minutes) at which rule condition should be evaluated. |
| 133 |
type: int |
| 134 |
time_window_in_minutes: |
| 135 |
description: Time window for which data needs to be fetched for query (should be greater than or equal to frequencyInMinutes). |
| 136 |
type: int |
| 137 |
enabled: |
| 138 |
description: |
| 139 |
- The flag which indicates whether the Log Search rule is enabled. |
| 140 |
type: str |
| 141 |
choices: |
| 142 |
- "False" |
| 143 |
- "True" |
| 144 |
auto_mitigate: |
| 145 |
description: |
| 146 |
- The flag that indicates whether the alert should be automatically resolved or not. |
| 147 |
type: bool |
| 148 |
description: |
| 149 |
description: |
| 150 |
- The description of the Log Search rule. |
| 151 |
type: str |
| 152 |
display_name: |
| 153 |
description: |
| 154 |
- The display name of the alert rule. |
| 155 |
type: str |
| 156 |
state: |
| 157 |
description: |
| 158 |
- State of the scheduled query rule |
| 159 |
- Use C(present) for creating/updating a scheduled query rule. |
| 160 |
- Use C(absent) for deleting a scheduled query rule. |
| 161 |
default: present |
| 162 |
type: str |
| 163 |
choices: |
| 164 |
- present |
| 165 |
- absent |
| 166 |
extends_documentation_fragment: |
| 167 |
- azure.azcollection.azure |
| 168 |
- azure.azcollection.azure_tags |
| 169 |
|
| 170 |
author: |
| 171 |
- Klaas Demter (@Klaas-) |
| 172 |
''' |
| 173 |
|
| 174 |
EXAMPLES = ''' |
| 175 |
- name: Add a scheduled query rule |
| 176 |
azure.azcollection.azure_rm_monitorscheduledqueryrules: |
| 177 |
state: present |
| 178 |
resource_group: myrg |
| 179 |
name: scheduled_query_rule_name |
| 180 |
location: eastus |
| 181 |
action: |
| 182 |
azns_action: |
| 183 |
action_group: |
| 184 |
- /subscriptions/<sub-id>/resourceGroups/myrg/providers/microsoft.insights/actionGroups/action_group_name |
| 185 |
email_subject: '' |
| 186 |
odata_type: >- |
| 187 |
Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.AlertingAction |
| 188 |
severity: 2 |
| 189 |
trigger: |
| 190 |
metric_trigger: |
| 191 |
metric_column: InstanceName,_ResourceId |
| 192 |
metric_trigger_type: Total |
| 193 |
threshold: 1 |
| 194 |
threshold_operator: GreaterThanOrEqual |
| 195 |
threshold: 10 |
| 196 |
threshold_operator: LessThan |
| 197 |
auto_mitigate: true |
| 198 |
description: 'Monitoring: Disks/logical volumes with less than 10% free space' |
| 199 |
display_name: Free_Space_Severity_2_Percentage |
| 200 |
enabled: "true" |
| 201 |
schedule: |
| 202 |
frequency_in_minutes: 5 |
| 203 |
time_window_in_minutes: 5 |
| 204 |
source: |
| 205 |
authorized_resources: [] |
| 206 |
data_source_id: "/subscriptions/<sub-id>/resourceGroups/myrg/providers/Microsoft.OperationalInsights/workspaces/log_analytics_workspace_name" |
| 207 |
query: > |
| 208 |
Perf |
| 209 |
| where CounterName == "% Free Space" |
| 210 |
| where InstanceName != "total" |
| 211 |
| summarize AggregatedValue = max(CounterValue) by bin(TimeGenerated, 5m), _ResourceId, InstanceName |
| 212 |
query_type: ResultCount |
| 213 |
|
| 214 |
|
| 215 |
- name: Add tag to existing scheduled query rule |
| 216 |
azure.azcollection.azure_rm_monitorscheduledqueryrules: |
| 217 |
state: present |
| 218 |
name: scheduled_query_rule_name |
| 219 |
resource_group: myrg |
| 220 |
append_tags: true |
| 221 |
tags: |
| 222 |
ThisIsAnAddedExampleTag: ExampleValue |
| 223 |
|
| 224 |
- name: Delete a scheduled query rule |
| 225 |
azure.azcollection.azure_rm_monitorscheduledqueryrules: |
| 226 |
state: absent |
| 227 |
name: scheduled_query_rule_name |
| 228 |
resource_group: myrg |
| 229 |
''' |
| 230 |
|
| 231 |
RETURN = ''' |
| 232 |
scheduledqueryrule: |
| 233 |
description: |
| 234 |
- Details of the scheduled query rule |
| 235 |
- Is null on state==absent (scheduled query rule does not exist or will be deleted) |
| 236 |
- Assumes you make legal changes in check mode |
| 237 |
type: dict |
| 238 |
returned: always |
| 239 |
sample: { |
| 240 |
"action": { |
| 241 |
"azns_action": { |
| 242 |
"action_group": [ |
| 243 |
"/subscriptions/<sub-id>/resourceGroups/myrg/providers/microsoft.insights/actionGroups/action_group_name" |
| 244 |
], |
| 245 |
"email_subject": "" |
| 246 |
}, |
| 247 |
"odata_type": \ |
| 248 |
"Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.AlertingAction", |
| 249 |
"severity": "2", |
| 250 |
"trigger": { |
| 251 |
"metric_trigger": { |
| 252 |
"metric_column": "InstanceName,_ResourceId", |
| 253 |
"metric_trigger_type": "Total", |
| 254 |
"threshold": 1.0, |
| 255 |
"threshold_operator": "GreaterThanOrEqual" |
| 256 |
}, |
| 257 |
"threshold": 10.0, |
| 258 |
"threshold_operator": "LessThan" |
| 259 |
} |
| 260 |
}, |
| 261 |
"auto_mitigate": true, |
| 262 |
"created_with_api_version": "2018-04-16", |
| 263 |
"description": "Monitoring: Disks/logical volumes with less than 10% free space", |
| 264 |
"display_name": "scheduled_query_alert_name", |
| 265 |
"enabled": "true", |
| 266 |
"id": \ |
| 267 |
"/subscriptions/<sub-id>/resourceGroups/myrg/providers/microsoft.insights/scheduledqueryrules/scheduled_query_alert_name", |
| 268 |
"last_updated_time": "2025-10-30T16:07:30.773011Z", |
| 269 |
"location": "eastus", |
| 270 |
"name": "scheduled_query_alert_name", |
| 271 |
"provisioning_state": "Succeeded", |
| 272 |
"schedule": { |
| 273 |
"frequency_in_minutes": 5, |
| 274 |
"time_window_in_minutes": 5 |
| 275 |
}, |
| 276 |
"source": { |
| 277 |
"authorized_resources": [], |
| 278 |
"data_source_id": \ |
| 279 |
"/subscriptions/<sub-id>/resourceGroups/myrg/providers/Microsoft.OperationalInsights/workspaces/log_analytics_workspace_name", |
| 280 |
"query": "actual query", |
| 281 |
"query_type": "ResultCount" |
| 282 |
}, |
| 283 |
"tags": {}, |
| 284 |
"type": "Microsoft.Insights/scheduledQueryRules" |
| 285 |
} |
| 286 |
''' |
| 287 |
|
| 288 |
from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt |
| 289 |
|
| 290 |
try: |
| 291 |
from azure.core.exceptions import ResourceNotFoundError |
| 292 |
|
| 293 |
except ImportError: |
| 294 |
|
| 295 |
pass |
| 296 |
|
| 297 |
AZURE_OBJECT_CLASS = 'scheduledqueryrule' |
| 298 |
|
| 299 |
azns_action_spec = dict( |
| 300 |
action_group=dict(type='list', elements='str'), |
| 301 |
email_subject=dict(type='str') |
| 302 |
) |
| 303 |
|
| 304 |
metric_trigger_spec = dict( |
| 305 |
metric_column=dict(type='str'), |
| 306 |
metric_trigger_type=dict(type='str', choices=['Consecutive', 'Total']), |
| 307 |
threshold=dict(type='float'), |
| 308 |
threshold_operator=dict(type='str', choices=[ |
| 309 |
"GreaterThanOrEqual", |
| 310 |
"GreaterThan", |
| 311 |
"LessThan", |
| 312 |
"Equal" |
| 313 |
]) |
| 314 |
) |
| 315 |
|
| 316 |
trigger_spec = dict( |
| 317 |
metric_trigger=dict(type='dict', options=metric_trigger_spec), |
| 318 |
threshold=dict(type='float'), |
| 319 |
threshold_operator=dict(type='str', choices=[ |
| 320 |
"GreaterThanOrEqual", |
| 321 |
"GreaterThan", |
| 322 |
"LessThan" |
| 323 |
]) |
| 324 |
) |
| 325 |
|
| 326 |
action_spec = dict( |
| 327 |
azns_action=dict(type='dict', options=azns_action_spec), |
| 328 |
odata_type=dict(type='str', choices=[ |
| 329 |
'AlertingAction', |
| 330 |
'LogToMetricAction', |
| 331 |
'Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.AlertingAction' |
| 332 |
]), |
| 333 |
severity=dict(type='int', choices=[0, 1, 2, 3, 4]), |
| 334 |
trigger=dict(type='dict', options=trigger_spec) |
| 335 |
) |
| 336 |
|
| 337 |
schedule_spec = dict( |
| 338 |
frequency_in_minutes=dict(type='int'), |
| 339 |
time_window_in_minutes=dict(type='int') |
| 340 |
) |
| 341 |
|
| 342 |
source_spec = dict( |
| 343 |
authorized_resources=dict(type='list', elements='str'), |
| 344 |
data_source_id=dict(type='str'), |
| 345 |
query=dict(type='str'), |
| 346 |
query_type=dict(type='str', choices=['ResultCount']) |
| 347 |
) |
| 348 |
|
| 349 |
|
| 350 |
class AzureRMMonitorscheduledqueryrule(AzureRMModuleBaseExt): |
| 351 |
"""Information class for an Azure RM Scheduled query rules""" |
| 352 |
|
| 353 |
def __init__(self): |
| 354 |
self.module_arg_spec = dict( |
| 355 |
name=dict(type='str', required=True), |
| 356 |
resource_group=dict(type='str', required=True), |
| 357 |
location=dict(type='str'), |
| 358 |
action=dict(type='dict', options=action_spec), |
| 359 |
auto_mitigate=dict(type='bool'), |
| 360 |
description=dict(type='str'), |
| 361 |
display_name=dict(type='str'), |
| 362 |
enabled=dict(type='str', choices=['True', 'False']), |
| 363 |
schedule=dict(type='dict', options=schedule_spec), |
| 364 |
source=dict(type='dict', options=source_spec), |
| 365 |
state=dict(type='str', choices=['present', 'absent'], default='present') |
| 366 |
) |
| 367 |
|
| 368 |
self.name = None |
| 369 |
self.resource_group = None |
| 370 |
self.location = None |
| 371 |
self.tags = None |
| 372 |
self.action = None |
| 373 |
self.auto_mitigate = None |
| 374 |
self.description = None |
| 375 |
self.display_name = None |
| 376 |
self.enabled = None |
| 377 |
self.schedule = None |
| 378 |
self.source = None |
| 379 |
self.state = None |
| 380 |
self.log_path = None |
| 381 |
self.log_mode = None |
| 382 |
|
| 383 |
self.results = dict( |
| 384 |
changed=False, |
| 385 |
scheduledqueryrule=dict(), |
| 386 |
diff=dict( |
| 387 |
before=None, |
| 388 |
after=None |
| 389 |
) |
| 390 |
) |
| 391 |
|
| 392 |
super(AzureRMMonitorscheduledqueryrule, self).__init__(derived_arg_spec=self.module_arg_spec, |
| 393 |
supports_check_mode=True, |
| 394 |
supports_tags=True) |
| 395 |
|
| 396 |
def exec_module(self, **kwargs): |
| 397 |
"""Main module execution method""" |
| 398 |
|
| 399 |
for key in list(self.module_arg_spec.keys()) + ['tags']: |
| 400 |
if hasattr(self, key): |
| 401 |
setattr(self, key, kwargs[key]) |
| 402 |
|
| 403 |
|
| 404 |
result = None |
| 405 |
result_compare = dict(compare=[]) |
| 406 |
before_dict = None |
| 407 |
|
| 408 |
|
| 409 |
before_dict = self.get_scheduled_query_rule() |
| 410 |
|
| 411 |
|
| 412 |
scheduled_query_rule_template = { |
| 413 |
"location": self.location, |
| 414 |
"action": self.action, |
| 415 |
"auto_mitigate": self.auto_mitigate, |
| 416 |
"description": self.description, |
| 417 |
"display_name": self.display_name, |
| 418 |
"enabled": self.enabled, |
| 419 |
"schedule": self.schedule, |
| 420 |
"source": self.source |
| 421 |
} |
| 422 |
|
| 423 |
scheduled_query_rule_input = {key: value for key, value in scheduled_query_rule_template.items() if value is not None} |
| 424 |
|
| 425 |
|
| 426 |
if self.state == 'present': |
| 427 |
if before_dict is None: |
| 428 |
|
| 429 |
|
| 430 |
if not self.location: |
| 431 |
resource_group = self.get_resource_group(self.resource_group) |
| 432 |
scheduled_query_rule_input['location'] = resource_group.location |
| 433 |
|
| 434 |
scheduled_query_rule_update = scheduled_query_rule_input |
| 435 |
|
| 436 |
if self.tags: |
| 437 |
scheduled_query_rule_update['tags'] = self.tags |
| 438 |
self.results['changed'] = True |
| 439 |
if self.check_mode: |
| 440 |
|
| 441 |
pass |
| 442 |
else: |
| 443 |
create_response = self.create_or_update(scheduled_query_rule_update) |
| 444 |
else: |
| 445 |
|
| 446 |
|
| 447 |
scheduled_query_rule_update = before_dict | scheduled_query_rule_input |
| 448 |
|
| 449 |
|
| 450 |
update_tags, update_tags_content = self.update_tags(before_dict.get('tags')) |
| 451 |
|
| 452 |
if update_tags or not self.default_compare({}, scheduled_query_rule_update, before_dict, '', result_compare): |
| 453 |
scheduled_query_rule_update['tags'] = update_tags_content |
| 454 |
|
| 455 |
self.results['changed'] = True |
| 456 |
if self.check_mode: |
| 457 |
|
| 458 |
pass |
| 459 |
else: |
| 460 |
create_response = self.create_or_update(scheduled_query_rule_update) |
| 461 |
|
| 462 |
if self.check_mode or not self.results['changed']: |
| 463 |
|
| 464 |
|
| 465 |
result = scheduled_query_rule_update |
| 466 |
else: |
| 467 |
|
| 468 |
result = create_response |
| 469 |
|
| 470 |
|
| 471 |
|
| 472 |
elif self.state == 'absent' and before_dict is not None: |
| 473 |
self.results['changed'] = True |
| 474 |
if self.check_mode: |
| 475 |
|
| 476 |
pass |
| 477 |
else: |
| 478 |
self.delete() |
| 479 |
|
| 480 |
self.results['diff']['before'] = before_dict |
| 481 |
self.results['diff']['after'] = result |
| 482 |
self.results['scheduledqueryrule'] = result |
| 483 |
|
| 484 |
return self.results |
| 485 |
|
| 486 |
def get_scheduled_query_rule(self): |
| 487 |
''' |
| 488 |
Gets the properties of the specified scheduled query rule. |
| 489 |
|
| 490 |
:return: List of Scheduled query rules |
| 491 |
''' |
| 492 |
self.log("Checking if scheduled query rule {0} in resource group {1} is present".format(self.name, |
| 493 |
self.resource_group)) |
| 494 |
|
| 495 |
result = None |
| 496 |
response = None |
| 497 |
|
| 498 |
try: |
| 499 |
response = self.monitor_management_client_scheduled_query_rules.scheduled_query_rules.get(rule_name=self.name, |
| 500 |
resource_group_name=self.resource_group) |
| 501 |
except ResourceNotFoundError as ex: |
| 502 |
self.log("Could not find scheduled query rule {0} in resource group {1}".format(self.name, self.resource_group)) |
| 503 |
if response: |
| 504 |
result = self.serialize_obj(response, AZURE_OBJECT_CLASS) |
| 505 |
|
| 506 |
return result |
| 507 |
|
| 508 |
def create_or_update(self, scheduled_query_rule_update): |
| 509 |
result = None |
| 510 |
response = None |
| 511 |
scheduled_query_rules = self.monitor_management_client_scheduled_query_rules.scheduled_query_rules |
| 512 |
try: |
| 513 |
response = scheduled_query_rules.create_or_update(resource_group_name=self.resource_group, |
| 514 |
rule_name=self.name, |
| 515 |
parameters=scheduled_query_rule_update, |
| 516 |
logging_enable=False) |
| 517 |
except Exception as ex: |
| 518 |
self.fail("Error creating or update scheduled query rule {0} in resource group {1}: {2}".format(self.name, self.resource_group, str(ex))) |
| 519 |
|
| 520 |
if response: |
| 521 |
result = self.serialize_obj(response, AZURE_OBJECT_CLASS) |
| 522 |
|
| 523 |
return result |
| 524 |
|
| 525 |
def delete(self): |
| 526 |
response = None |
| 527 |
try: |
| 528 |
response = self.monitor_management_client_scheduled_query_rules.scheduled_query_rules.delete(resource_group_name=self.resource_group, |
| 529 |
rule_name=self.name) |
| 530 |
except Exception as ex: |
| 531 |
self.fail("Error deleting scheduled query rule {0} in resource group {1}: {2}".format(self.name, self.resource_group, str(ex))) |
| 532 |
|
| 533 |
return response |
| 534 |
|
| 535 |
|
| 536 |
def main(): |
| 537 |
"""Main execution""" |
| 538 |
AzureRMMonitorscheduledqueryrule() |
| 539 |
|
| 540 |
|
| 541 |
if __name__ == '__main__': |
| 542 |
main() |