Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2019 Yuwei Zhou, <[email protected]>
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_loganalyticsworkspace
14 version_added: "0.1.2"
15 short_description: Manage Azure Log Analytics workspaces
16 description:
17 - Create, delete Azure Log Analytics workspaces.
18 options:
19 resource_group:
20 description:
21 - Name of resource group.
22 required: true
23 type: str
24 name:
25 description:
26 - Name of the workspace.
27 required: true
28 type: str
29 state:
30 description:
31 - Assert the state of the image. Use C(present) to create or update a image and C(absent) to delete an image.
32 default: present
33 type: str
34 choices:
35 - absent
36 - present
37 location:
38 description:
39 - Resource location.
40 type: str
41 identity:
42 description:
43 - Identity for Azure Recovery Service Vault.
44 type: dict
45 version_added: '3.0.0'
46 suboptions:
47 type:
48 description:
49 - Type of the managed identity
50 choices:
51 - SystemAssigned
52 - UserAssigned
53 - None
54 default: None
55 type: str
56 user_assigned_identity:
57 description:
58 - User Assigned Managed Identity associated to this resource
59 required: false
60 type: str
61 sku:
62 description:
63 - The SKU of the workspace.
64 type: str
65 choices:
66 - free
67 - standard
68 - premium
69 - unlimited
70 - per_node
71 - per_gb2018
72 - standalone
73 default: per_gb2018
74 retention_in_days:
75 description:
76 - The workspace data retention in days.
77 - -1 means Unlimited retention for I(sku=unlimited).
78 - 730 days is the maximum allowed for all other SKUs.
79 type: int
80 intelligence_packs:
81 description:
82 - Manage intelligence packs possible for this workspace.
83 - Enable one pack by setting it to C(true). For example "Backup:true".
84 - Disable one pack by setting it to C(false). For example "Backup:false".
85 - Other intelligence packs not list in this property will not be changed.
86 type: dict
87 force:
88 description:
89 - Deletes the workspace without the recovery option. A workspace that was deleted with this flag cannot be recovered.
90 default: false
91 type: bool
92 extends_documentation_fragment:
93 - azure.azcollection.azure
94 - azure.azcollection.azure_tags
95
96 author:
97 - Yuwei Zhou (@yuwzho)
98 '''
99
100 EXAMPLES = '''
101 - name: Create a workspace with backup enabled
102 azure_rm_loganalyticsworkspace:
103 resource_group: myResourceGroup
104 name: myLogAnalyticsWorkspace
105 intelligence_pack:
106 Backup: true
107 '''
108
109 RETURN = '''
110 id:
111 description:
112 - Workspace resource path.
113 type: str
114 returned: success
115 example: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.OperationalInsights/workspaces/m
116 yLogAnalyticsWorkspace"
117 location:
118 description:
119 - Resource location.
120 type: str
121 returned: success
122 example: eastus
123 sku:
124 description:
125 - The SKU of the workspace.
126 type: str
127 returned: success
128 example: "per_gb2018"
129 retention_in_days:
130 description:
131 - The workspace data retention in days.
132 - -1 means Unlimited retention for I(sku=unlimited).
133 - 730 days is the maximum allowed for all other SKUs.
134 type: int
135 returned: success
136 example: 40
137 intelligence_packs:
138 description:
139 - Lists all the intelligence packs possible and whether they are enabled or disabled for a given workspace.
140 type: list
141 returned: success
142 example: ['name': 'CapacityPerformance', 'enabled': true]
143 management_groups:
144 description:
145 - Management groups connected to the workspace.
146 type: dict
147 returned: success
148 example: {'value': []}
149 shared_keys:
150 description:
151 - Shared keys for the workspace.
152 type: dict
153 returned: success
154 example: {
155 'primarySharedKey': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
156 'secondarySharedKey': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
157 }
158 usages:
159 description:
160 - Usage metrics for the workspace.
161 type: dict
162 returned: success
163 example: {
164 'value': [
165 {
166 'name': {
167 'value': 'DataAnalyzed',
168 'localizedValue': 'Data Analyzed'
169 },
170 'unit': 'Bytes',
171 'currentValue': 0,
172 'limit': 524288000,
173 'nextResetTime': '2017-10-03T00:00:00Z',
174 'quotaPeriod': 'P1D'
175 }
176 ]
177 }
178 ''' # NOQA
179
180 from ansible.module_utils.common.dict_transformations import _snake_to_camel, _camel_to_snake
181
182 try:
183 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
184 from azure.core.exceptions import ResourceNotFoundError
185 from azure.mgmt.loganalytics.models import (Identity, UserIdentityProperties)
186 except ImportError:
187 # This is handled in azure_rm_common
188 pass
189
190
191 class AzureRMLogAnalyticsWorkspace(AzureRMModuleBaseExt):
192
193 def __init__(self):
194
195 self.module_arg_spec = dict(
196 resource_group=dict(type='str', required=True),
197 name=dict(type='str', required=True),
198 state=dict(type='str', default='present', choices=['present', 'absent']),
199 identity=dict(
200 type='dict',
201 options=self.managed_identity_single_spec
202 ),
203 location=dict(type='str'),
204 sku=dict(type='str', default='per_gb2018', choices=['free', 'standard', 'premium', 'unlimited', 'per_node', 'per_gb2018', 'standalone']),
205 retention_in_days=dict(type='int'),
206 intelligence_packs=dict(type='dict'),
207 force=dict(type='bool', default=False)
208 )
209
210 self.results = dict(
211 changed=False,
212 id=None
213 )
214
215 self.resource_group = None
216 self.name = None
217 self.state = None
218 self.location = None
219 self.identity = None
220 self.sku = None
221 self.retention_in_days = None
222 self.intelligence_packs = None
223 self.force = None
224 self._managed_identity = None
225
226 super(AzureRMLogAnalyticsWorkspace, self).__init__(self.module_arg_spec, supports_check_mode=True)
227
228 @property
229 def managed_identity(self):
230 if not self._managed_identity:
231 self._managed_identity = {"identity": Identity,
232 "user_assigned": UserIdentityProperties
233 }
234 return self._managed_identity
235
236 def exec_module(self, **kwargs):
237
238 for key in list(self.module_arg_spec.keys()) + ['tags']:
239 setattr(self, key, kwargs[key])
240
241 self.results = dict()
242 changed = False
243
244 if not self.location:
245 resource_group = self.get_resource_group(self.resource_group)
246 self.location = resource_group.location
247
248 if self.sku == 'per_gb2018':
249 self.sku = 'PerGB2018'
250 else:
251 self.sku = _snake_to_camel(self.sku)
252 workspace = self.get_workspace()
253 update_identity = False
254 identity = None
255 if self.identity:
256 old_identity = workspace and workspace.identity.as_dict() or None
257 update_identity, identity = self.update_single_managed_identity(curr_identity=old_identity,
258 new_identity=self.identity)
259 if not workspace and self.state == 'present':
260 changed = True
261 workspace = self.log_analytics_models.Workspace(sku=self.log_analytics_models.WorkspaceSku(name=self.sku),
262 retention_in_days=self.retention_in_days,
263 location=self.location,
264 identity=identity,
265 tags=self.tags)
266 if not self.check_mode:
267 workspace = self.create_workspace(workspace)
268 elif workspace and self.state == 'present':
269 if workspace.retention_in_days != self.retention_in_days:
270 changed = True
271 results = dict()
272 update_tags, results['tags'] = self.update_tags(workspace.tags)
273 if update_tags:
274 changed = True
275 if update_identity:
276 changed = True
277 if not self.check_mode and changed:
278 workspace = self.log_analytics_models.Workspace(sku=self.log_analytics_models.WorkspaceSku(name=self.sku),
279 retention_in_days=self.retention_in_days,
280 location=self.location,
281 identity=identity,
282 tags=results['tags'])
283 workspace = self.create_workspace(workspace)
284 elif workspace and self.state == 'absent':
285 changed = True
286 workspace = None
287 if not self.check_mode:
288 self.delete_workspace()
289 if workspace and workspace.id:
290 self.results = self.to_dict(workspace)
291 self.results['intelligence_packs'] = self.list_intelligence_packs()
292 self.results['management_groups'] = self.list_management_groups()
293 self.results['usages'] = self.list_usages()
294 self.results['shared_keys'] = self.get_shared_keys()
295 # handle the intelligence pack
296 if workspace and workspace.id and self.intelligence_packs:
297 intelligence_packs = self.results['intelligence_packs']
298 for key in self.intelligence_packs.keys():
299 enabled = self.intelligence_packs[key]
300 for x in intelligence_packs:
301 if x['name'].lower() == key.lower():
302 if x['enabled'] != enabled:
303 changed = True
304 if not self.check_mode:
305 self.change_intelligence(x['name'], enabled)
306 x['enabled'] = enabled
307 break
308 self.results['changed'] = changed
309 return self.results
310
311 def create_workspace(self, workspace):
312 try:
313 poller = self.log_analytics_client.workspaces.begin_create_or_update(self.resource_group, self.name, workspace)
314 return self.get_poller_result(poller)
315 except Exception as exc:
316 self.fail('Error when creating workspace {0} - {1}'.format(self.name, str(exc)))
317
318 def get_workspace(self):
319 try:
320 return self.log_analytics_client.workspaces.get(self.resource_group, self.name)
321 except ResourceNotFoundError:
322 pass
323
324 def delete_workspace(self):
325 try:
326 poller = self.log_analytics_client.workspaces.begin_delete(self.resource_group,
327 self.name,
328 force=self.force)
329 return self.get_poller_result(poller)
330 except Exception as exc:
331 self.fail('Error when deleting workspace {0} - {1}'.format(self.name, str(exc)))
332
333 def to_dict(self, workspace):
334 result = workspace.as_dict()
335 result['sku'] = _camel_to_snake(workspace.sku.name)
336 return result
337
338 def list_intelligence_packs(self):
339 try:
340 response = self.log_analytics_client.intelligence_packs.list(self.resource_group, self.name)
341 return [x.as_dict() for x in response]
342 except Exception as exc:
343 self.fail('Error when listing intelligence packs {0}'.format(str(exc)))
344
345 def change_intelligence(self, key, value):
346 try:
347 if value:
348 self.log_analytics_client.intelligence_packs.enable(self.resource_group, self.name, key)
349 else:
350 self.log_analytics_client.intelligence_packs.disable(self.resource_group, self.name, key)
351 except Exception as exc:
352 self.fail('Error when changing intelligence pack {0} - {1}'.format(key, str(exc)))
353
354 def list_management_groups(self):
355 result = []
356 try:
357 response = self.log_analytics_client.management_groups.list(self.resource_group, self.name)
358 while True:
359 result.append(response.next().as_dict())
360 except StopIteration:
361 pass
362 except Exception as exc:
363 self.fail('Error when listing management groups {0}'.format(str(exc)))
364 return result
365
366 def list_usages(self):
367 result = []
368 try:
369 response = self.log_analytics_client.usages.list(self.resource_group, self.name)
370 while True:
371 result.append(response.next().as_dict())
372 except StopIteration:
373 pass
374 except Exception as exc:
375 self.fail('Error when listing usages {0}'.format(str(exc)))
376 return result
377
378 def get_shared_keys(self):
379 try:
380 return self.log_analytics_client.shared_keys.get_shared_keys(self.resource_group, self.name).as_dict()
381 except Exception as exc:
382 self.fail('Error when getting shared key {0}'.format(str(exc)))
383
384
385 def main():
386 AzureRMLogAnalyticsWorkspace()
387
388
389 if __name__ == '__main__':
390 main()