Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_monitordiagnosticsetting.py

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2021 Ross Bender (@l3ender)
4 #
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10
11 DOCUMENTATION = '''
12 ---
13 module: azure_rm_monitordiagnosticsetting
14 version_added: "1.10.0"
15 short_description: Create, update, or manage Azure Monitor diagnostic settings.
16
17 description:
18 - Create, update, or manage Azure Monitor diagnostic settings for any type of resource.
19
20 options:
21 name:
22 description:
23 - The name of the diagnostic settings.
24 type: str
25 required: true
26 resource:
27 description:
28 - The resource which will be monitored with the diagnostic setting.
29 - It can be a string containing the resource ID.
30 - It can be a dictionary containing I(name), I(type), I(resource_group), and optionally I(subscription_id).
31 - I(name). The resource name.
32 - I(type). The resource type including namespace, such as 'Microsoft.Network/virtualNetworks'.
33 - I(resource_group). The resource group containing the resource.
34 - I(subscription_id). The subscription ID containing the resource. If none is specified, the credential's subscription ID will be used.
35 type: raw
36 required: true
37 storage_account:
38 description:
39 - A storage account which will receive the diagnostic logs.
40 - It can be a string containing the storage account resource ID.
41 - It can be a dictionary containing I(name) and optionally I(subscription_id) and I(resource_group).
42 - At least one of I(storage_account), I(log_analytics), or I(event_hub) must be specified for the diagnostic setting.
43 type: raw
44 log_analytics:
45 description:
46 - A log analytics workspace which will receive the diagnostic logs.
47 - It can be a string containing the log analytics workspace resource ID.
48 - It can be a dictionary containing I(name) and optionally I(subscription_id) and I(resource_group).
49 - At least one of I(storage_account), I(log_analytics), or I(event_hub) must be specified for the diagnostic setting.
50 type: raw
51 event_hub:
52 description:
53 - An event hub which will receive the diagnostic logs.
54 - At least one of I(storage_account), I(log_analytics), or I(event_hub) must be specified for the diagnostic setting.
55 type: dict
56 suboptions:
57 namespace:
58 description:
59 - The event hub namespace.
60 type: str
61 required: true
62 policy:
63 description:
64 - The shared access policy.
65 type: str
66 required: true
67 hub:
68 description:
69 - An event hub name to receive logs. If none is specified, the default event hub will be selected.
70 type: str
71 resource_group:
72 description:
73 - The resource group containing the event hub. If none is specified, the resource group of the I(resource) parameter will be used.
74 type: str
75 subscription_id:
76 description:
77 - The subscription ID containing the event hub. If none is specified, the subscription ID of the I(resource) parameter will be used.
78 type: str
79 logs:
80 description:
81 - The list of log setttings.
82 - At least one of I(metrics) or I(logs) must be specified for the diagnostic setting.
83 type: list
84 elements: dict
85 suboptions:
86 category:
87 description:
88 - Name of a Management Group Diagnostic Log category for a resource type this setting is applied to.
89 type: str
90 category_group:
91 description:
92 - Name of a Management Group Diagnostic Log category group for a resource type this setting is applied to.
93 type: str
94 enabled:
95 description:
96 - Whether the log is enabled.
97 type: bool
98 default: true
99 retention_policy:
100 description:
101 - The retention policy for this log.
102 type: dict
103 suboptions:
104 days:
105 description:
106 - The number of days for the retention policy.
107 type: int
108 default: 0
109 enabled:
110 description:
111 - Whether the retention policy is enabled.
112 type: bool
113 default: true
114 metrics:
115 description:
116 - The list of metric setttings.
117 - At least one of I(metrics) or I(logs) must be specified for the diagnostic setting.
118 type: list
119 elements: dict
120 suboptions:
121 category:
122 description:
123 - Name of a Diagnostic Metric category for a resource type this setting is applied to.
124 type: str
125 enabled:
126 description:
127 - Whether the metric category is enabled.
128 type: bool
129 default: true
130 retention_policy:
131 description:
132 - The retention policy for this metric.
133 type: dict
134 suboptions:
135 days:
136 description:
137 - The number of days for the retention policy.
138 type: int
139 default: 0
140 enabled:
141 description:
142 - Whether the retention policy is enabled.
143 type: bool
144 default: true
145 state:
146 description:
147 - State of the private endpoint DNS zone group. Use C(present) to create or update and C(absent) to delete.
148 default: present
149 type: str
150 choices:
151 - absent
152 - present
153
154 extends_documentation_fragment:
155 - azure.azcollection.azure
156
157 author:
158 - Ross Bender (@l3ender)
159 '''
160
161 EXAMPLES = '''
162 - name: Create storage-based diagnostic setting for a virtual network
163 azure_rm_monitordiagnosticsetting:
164 name: "logs-storage"
165 resource: "{{ vnet_output.state.id }}"
166 storage_account: "{{ storage_output.state.id }}"
167 logs:
168 - category_group: "allLogs"
169 metrics:
170 - category: "AllMetrics"
171
172 - name: Create diagnostic setting for webapp with log analytics, event hub, and storage
173 azure_rm_monitordiagnosticsetting:
174 name: "webapp-logs"
175 resource:
176 name: "my-webapp"
177 type: "Microsoft.Web/sites"
178 resource_group: "my-webapp-resource-group"
179 event_hub:
180 namespace: "my-event-hub"
181 policy: "RootManageSharedAccessKey"
182 log_analytics:
183 name: "my-log-analytics-workspace"
184 resource_group: "my-log-analytics-workspace-resource-group"
185 storage_account:
186 name: "mystorageaccount"
187 logs:
188 - category: "AppServiceHTTPLogs"
189 - category: "AppServiceConsoleLogs"
190 - category: "AppServiceAppLogs"
191 - category: "AppServiceAuditLogs"
192 - category: "AppServiceIPSecAuditLogs"
193 - category: "AppServicePlatformLogs"
194
195 - name: Delete diagnostic setting
196 azure_rm_monitordiagnosticsetting:
197 name: "webapp-logs"
198 resource:
199 name: "my-webapp"
200 type: "Microsoft.Web/sites"
201 resource_group: "my-webapp-resource-group"
202 state: "absent"
203 '''
204
205 RETURN = '''
206 state:
207 description:
208 - The state of the diagnostic setting.
209 returned: always
210 type: dict
211 contains:
212 id:
213 description:
214 - ID of the diagnostic setting.
215 sample: >-
216 /subscriptions/xxx/resourcegroups/my-resource-group/providers/microsoft.network/applicationgateways/my-appgw/
217 providers/microsoft.insights/diagnosticSettings/my-diagnostic-setting
218 returned: always
219 type: str
220 name:
221 description:
222 - Name of the diagnostic setting.
223 returned: always
224 type: str
225 sample: my-diagnostic-setting
226 logs:
227 description:
228 - Enabled log configurations for the diagnostic setting.
229 returned: always
230 type: list
231 elements: dict
232 contains:
233 category:
234 description:
235 - Name of a Management Group Diagnostic Log category for a resource type this setting is applied to.
236 type: str
237 returned: always
238 category_group:
239 description:
240 - Name of a Management Group Diagnostic Log category group for a resource type this setting is applied to.
241 type: str
242 returned: always
243 enabled:
244 description:
245 - Whether this log is enabled.
246 type: bool
247 returned: always
248 retention_policy:
249 description:
250 - The retention policy for this log.
251 type: dict
252 returned: always
253 contains:
254 enabled:
255 description:
256 - Whether the retention policy is enabled.
257 type: bool
258 returned: always
259 days:
260 description:
261 - The number of days for the retention policy.
262 type: int
263 returned: always
264 metrics:
265 description:
266 - Enabled metric configurations for the diagnostic setting.
267 returned: always
268 type: list
269 elements: dict
270 contains:
271 category:
272 description:
273 - Name of a Diagnostic Metric category for a resource type this setting is applied to.
274 type: str
275 returned: always
276 enabled:
277 description:
278 - Whether the metric category is enabled.
279 type: bool
280 returned: always
281 retention_policy:
282 description:
283 - The retention policy for the metric category.
284 type: dict
285 returned: always
286 contains:
287 enabled:
288 description:
289 - Whether the retention policy is enabled.
290 type: bool
291 returned: always
292 days:
293 description:
294 - The number of days for the retention policy.
295 type: int
296 returned: always
297 event_hub:
298 description:
299 - The event hub for the diagnostic setting, if configured.
300 returned: always
301 type: dict
302 contains:
303 id:
304 description:
305 - ID of the event hub namespace.
306 returned: always
307 type: str
308 sample: >-
309 /subscriptions/xxx/resourceGroups/my-resource-group/providers/Microsoft.EventHub/namespaces/my-event-hub-namespace
310 namespace:
311 description:
312 - Name of the event hub namespace.
313 returned: always
314 type: str
315 sample: my-event-hub-namespace
316 hub:
317 description:
318 - Name of the hub within the namespace.
319 returned: always
320 type: str
321 sample: my-event-hub
322 policy:
323 description:
324 - Name of the event hub shared access policy.
325 returned: always
326 type: str
327 sample: RootManageSharedAccessKey
328 log_analytics:
329 description:
330 - The log analytics workspace for the diagnostic setting, if configured.
331 returned: always
332 type: dict
333 contains:
334 id:
335 description:
336 - ID of the log analytics workspace.
337 returned: always
338 type: str
339 sample: >-
340 /subscriptions/xxx/resourcegroups/my-resource-group/providers/microsoft.operationalinsights/workspaces/my-log-analytics-workspace
341 storage_account:
342 description:
343 - The storage account for the diagnostic setting, if configured.
344 returned: always
345 type: dict
346 contains:
347 id:
348 description:
349 - ID of the storage account.
350 returned: always
351 type: str
352 sample: >-
353 /subscriptions/xxx/resourceGroups/my-resource-group/providers/Microsoft.Storage/storageAccounts/my-storage-account
354 '''
355
356 try:
357 from azure.mgmt.core.tools import (parse_resource_id, resource_id)
358 from azure.core.polling import LROPoller
359 except ImportError:
360 # This is handled in azure_rm_common
361 pass
362
363 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
364
365
366 event_hub_spec = dict(
367 namespace=dict(type="str", required=True),
368 policy=dict(type="str", required=True),
369 hub=dict(type="str"),
370 resource_group=dict(type="str"),
371 subscription_id=dict(type="str"),
372 )
373
374 retention_policy_spec = dict(
375 days=dict(type="int", default=0),
376 enabled=dict(type="bool", default=True),
377 )
378
379 logs_spec = dict(
380 category=dict(type="str"),
381 category_group=dict(type="str"),
382 enabled=dict(type="bool", default=True),
383 retention_policy=dict(type="dict", options=retention_policy_spec),
384 )
385
386 metrics_spec = dict(
387 category=dict(type="str"),
388 enabled=dict(type="bool", default=True),
389 retention_policy=dict(type="dict", options=retention_policy_spec),
390 )
391
392
393 class Actions:
394 NoAction, Create, Update, Delete = range(4)
395
396
397 class AzureRMMonitorDiagnosticSetting(AzureRMModuleBaseExt):
398
399 def __init__(self):
400
401 self.module_arg_spec = dict(
402 name=dict(type="str", required=True),
403 resource=dict(type="raw", required=True),
404 storage_account=dict(type="raw"),
405 log_analytics=dict(type="raw"),
406 event_hub=dict(type="dict", options=event_hub_spec),
407 logs=dict(type="list", elements="dict", options=logs_spec),
408 metrics=dict(type="list", elements="dict", options=metrics_spec),
409 state=dict(type="str", default="present", choices=["present", "absent"]),
410 )
411
412 self.name = None
413 self.resource = None
414 self.state = None
415 self.parameters = dict()
416 self.results = dict(
417 changed=False,
418 state=dict()
419 )
420 self.to_do = Actions.NoAction
421
422 super(AzureRMMonitorDiagnosticSetting, self).__init__(self.module_arg_spec,
423 required_if=[
424 ("state", "present", ("storage_account", "log_analytics", "event_hub"), True),
425 ("state", "present", ("logs", "metrics"), True),
426 ],
427 supports_tags=False,
428 supports_check_mode=True)
429
430 def exec_module(self, **kwargs):
431 for key in self.module_arg_spec:
432 if hasattr(self, key):
433 setattr(self, key, kwargs[key])
434 elif kwargs[key] is not None:
435 self.parameters[key] = kwargs[key]
436
437 self.process_parameters()
438
439 old_response = self.get_item()
440
441 if old_response is None or not old_response:
442 if self.state == "present":
443 self.to_do = Actions.Create
444 else:
445 if self.state == "absent":
446 self.to_do = Actions.Delete
447 else:
448 self.results["compare"] = []
449 if not self.idempotency_check(old_response, self.diagnostic_setting_to_dict(self.parameters)):
450 self.to_do = Actions.Update
451
452 if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
453 self.results["changed"] = True
454 if self.check_mode:
455 return self.results
456 response = self.create_update_setting()
457 elif self.to_do == Actions.Delete:
458 self.results["changed"] = True
459 if self.check_mode:
460 return self.results
461 response = self.delete_setting()
462 else:
463 self.results["changed"] = False
464 response = old_response
465
466 if response is not None:
467 self.results["state"] = response
468
469 return self.results
470
471 def process_parameters(self):
472 if isinstance(self.resource, dict):
473 if "/" not in self.resource.get("type"):
474 self.fail("resource type parameter must include namespace, such as 'Microsoft.Network/virtualNetworks'")
475 self.resource = resource_id(subscription=self.resource.get("subscription_id", self.subscription_id),
476 resource_group=self.resource.get("resource_group"),
477 namespace=self.resource.get("type").split("/")[0],
478 type=self.resource.get("type").split("/")[1],
479 name=self.resource.get("name"))
480
481 parsed_resource = parse_resource_id(self.resource)
482
483 storage_account = self.parameters.pop("storage_account", None)
484 if storage_account:
485 if isinstance(storage_account, dict):
486 if not storage_account.get("name"):
487 self.fail("storage_account must contain 'name'")
488
489 storage_account_id = resource_id(subscription=storage_account.get("subscription_id", parsed_resource.get("subscription")),
490 resource_group=storage_account.get("resource_group", parsed_resource.get("resource_group")),
491 namespace="Microsoft.Storage",
492 type="storageAccounts",
493 name=storage_account.get("name"))
494 else:
495 storage_account_id = storage_account
496
497 self.parameters["storage_account_id"] = storage_account_id
498
499 log_analytics = self.parameters.pop("log_analytics", None)
500 if log_analytics:
501 if isinstance(log_analytics, dict):
502 if not log_analytics.get("name"):
503 self.fail("log_analytics must contain 'name'")
504
505 log_analytics_id = resource_id(subscription=log_analytics.get("subscription_id", parsed_resource.get("subscription")),
506 resource_group=log_analytics.get("resource_group", parsed_resource.get("resource_group")),
507 namespace="microsoft.operationalinsights",
508 type="workspaces",
509 name=log_analytics.get("name"))
510 else:
511 log_analytics_id = log_analytics
512
513 self.parameters["workspace_id"] = log_analytics_id
514
515 event_hub = self.parameters.pop("event_hub", None)
516 if event_hub:
517 hub_subscription_id = event_hub.get("subscription_id") if event_hub.get("subscription_id") else parsed_resource.get("subscription")
518 hub_resource_group = event_hub.get("resource_group") if event_hub.get("resource_group") else parsed_resource.get("resource_group")
519 auth_rule_id = resource_id(subscription=hub_subscription_id,
520 resource_group=hub_resource_group,
521 namespace="Microsoft.EventHub",
522 type="namespaces",
523 name=event_hub.get("namespace"),
524 child_type_1="authorizationrules",
525 child_name_1=event_hub.get("policy"))
526 self.parameters["event_hub_authorization_rule_id"] = auth_rule_id
527 self.parameters["event_hub_name"] = event_hub.get("hub")
528
529 def get_item(self):
530 self.log("Get diagnostic setting for {0} in {1}".format(self.name, self.resource))
531
532 try:
533 item = self.monitor_diagnostic_settings_client.diagnostic_settings.get(resource_uri=self.resource, name=self.name)
534 return self.diagnostic_setting_to_dict(item)
535 except Exception:
536 self.log("Did not find diagnostic setting for {0} in {1}".format(self.name, self.resource))
537
538 return None
539
540 def create_update_setting(self):
541 try:
542 response = self.monitor_diagnostic_settings_client.diagnostic_settings.create_or_update(resource_uri=self.resource,
543 name=self.name,
544 parameters=self.parameters)
545 if isinstance(response, LROPoller):
546 response = self.get_poller_result(response)
547
548 return self.diagnostic_setting_to_dict(response)
549 except Exception as exc:
550 self.fail("Error creating or updating diagnostic setting {0} for resource {1}: {2}".format(self.name, self.resource, str(exc)))
551
552 def delete_setting(self):
553 try:
554 response = self.monitor_diagnostic_settings_client.diagnostic_settings.delete(resource_uri=self.resource,
555 name=self.name)
556 if isinstance(response, LROPoller):
557 response = self.get_poller_result(response)
558
559 return response
560 except Exception as exc:
561 self.fail("Error deleting diagnostic setting {0} for resource {1}: {2}".format(self.name, self.resource, str(exc)))
562
563 def diagnostic_setting_to_dict(self, diagnostic_setting):
564 setting_dict = diagnostic_setting if isinstance(diagnostic_setting, dict) else diagnostic_setting.as_dict()
565 result = dict(
566 id=setting_dict.get("id"),
567 name=setting_dict.get("name"),
568 event_hub=self.event_hub_dict(setting_dict),
569 storage_account=self.storage_dict(setting_dict.get("storage_account_id")),
570 log_analytics=self.log_analytics_dict(setting_dict.get("workspace_id")),
571 logs=[self.log_config_to_dict(log) for log in setting_dict.get("logs", [])],
572 metrics=[self.metric_config_to_dict(metric) for metric in setting_dict.get("metrics", [])],
573 )
574 return self.remove_disabled_config(result)
575
576 def remove_disabled_config(self, diagnostic_setting):
577 diagnostic_setting["logs"] = [log for log in diagnostic_setting.get("logs", []) if log.get("enabled")]
578 diagnostic_setting["metrics"] = [metric for metric in diagnostic_setting.get("metrics", []) if metric.get("enabled")]
579 return diagnostic_setting
580
581 def event_hub_dict(self, setting_dict):
582 auth_rule_id = setting_dict.get("event_hub_authorization_rule_id")
583 if auth_rule_id:
584 parsed_rule_id = parse_resource_id(auth_rule_id)
585 return dict(
586 id=resource_id(subscription=parsed_rule_id.get("subscription"),
587 resource_group=parsed_rule_id.get("resource_group"),
588 namespace=parsed_rule_id.get("namespace"),
589 type=parsed_rule_id.get("type"),
590 name=parsed_rule_id.get("name")),
591 namespace=parsed_rule_id.get("name"),
592 hub=setting_dict.get("event_hub_name"),
593 policy=parsed_rule_id.get("resource_name"),
594 )
595 return None
596
597 def storage_dict(self, storage_account_id):
598 if storage_account_id:
599 return dict(
600 id=storage_account_id,
601 )
602 return None
603
604 def log_analytics_dict(self, workspace_id):
605 if workspace_id:
606 return dict(
607 id=workspace_id,
608 )
609 return None
610
611 def log_config_to_dict(self, log_config):
612 return dict(
613 category=log_config.get("category"),
614 category_group=log_config.get("category_group"),
615 enabled=log_config.get("enabled"),
616 retention_policy=self.retention_policy_to_dict(log_config.get("retention_policy")),
617 )
618
619 def metric_config_to_dict(self, metric_config):
620 return dict(
621 category=metric_config.get("category"),
622 enabled=metric_config.get("enabled"),
623 retention_policy=self.retention_policy_to_dict(metric_config.get("retention_policy")),
624 )
625
626 def retention_policy_to_dict(self, policy):
627 if policy:
628 return dict(
629 days=policy.get("days"),
630 enabled=policy.get("enabled"),
631 )
632 return None
633
634
635 def main():
636 AzureRMMonitorDiagnosticSetting()
637
638
639 if __name__ == "__main__":
640 main()