Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2019 Zim Kalinowski, (@zikalino)
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_hdinsightcluster
14 version_added: "0.1.2"
15 short_description: Manage Azure HDInsight Cluster instance
16 description:
17 - Create, update and delete instance of Azure HDInsight Cluster.
18
19 options:
20 resource_group:
21 description:
22 - The name of the resource group.
23 required: True
24 type: str
25 name:
26 description:
27 - The name of the cluster.
28 required: True
29 type: str
30 location:
31 description:
32 - Resource location. If not set, location from the resource group will be used as default.
33 type: str
34 cluster_version:
35 description:
36 - The version of the cluster. For example C(3.6).
37 type: str
38 os_type:
39 description:
40 - The type of operating system.
41 type: str
42 choices:
43 - 'linux'
44 - 'Linux'
45 tier:
46 description:
47 - The cluster tier.
48 type: str
49 choices:
50 - 'standard'
51 - 'premium'
52 cluster_definition:
53 description:
54 - The cluster definition.
55 type: dict
56 suboptions:
57 kind:
58 description:
59 - The type of cluster.
60 type: str
61 choices:
62 - hadoop
63 - spark
64 - hbase
65 - storm
66 gateway_rest_username:
67 description:
68 - Gateway REST user name.
69 type: str
70 gateway_rest_password:
71 description:
72 - Gateway REST password.
73 type: str
74 compute_profile_roles:
75 description:
76 - The list of roles in the cluster.
77 type: list
78 elements: dict
79 suboptions:
80 name:
81 description:
82 - The name of the role.
83 type: str
84 choices:
85 - 'headnode'
86 - 'workernode'
87 - 'zookeepernode'
88 min_instance_count:
89 description:
90 - The minimum instance count of the cluster.
91 type: int
92 target_instance_count:
93 description:
94 - The instance count of the cluster.
95 type: int
96 vm_size:
97 description:
98 - The size of the VM.
99 type: str
100 linux_profile:
101 description:
102 - The Linux OS profile.
103 type: dict
104 suboptions:
105 username:
106 description:
107 - SSH user name.
108 type: str
109 password:
110 description:
111 - SSH password.
112 type: str
113 identity:
114 description:
115 - Identity for the HDInsight Cluster.
116 type: dict
117 version_added: '3.0.0'
118 suboptions:
119 type:
120 description:
121 - Type of the managed identity
122 choices:
123 - SystemAssigned
124 - UserAssigned
125 - SystemAssigned, UserAssigned
126 - None
127 default: None
128 type: str
129 user_assigned_identities:
130 description:
131 - User Assigned Managed Identities and its options
132 required: false
133 type: dict
134 default: {}
135 suboptions:
136 id:
137 description:
138 - List of the user assigned identities IDs associated to the HDInsight Cluster
139 required: false
140 type: list
141 elements: str
142 default: []
143 append:
144 description:
145 - If the list of identities has to be appended to current identities (true) or if it has to replace current identities (false)
146 required: false
147 type: bool
148 default: True
149 storage_accounts:
150 description:
151 - The list of storage accounts in the cluster.
152 type: list
153 elements: dict
154 suboptions:
155 name:
156 description:
157 - Blob storage endpoint. For example storage_account_name.blob.core.windows.net.
158 type: str
159 is_default:
160 description:
161 - Whether or not the storage account is the default storage account.
162 type: bool
163 container:
164 description:
165 - The container in the storage account.
166 type: str
167 key:
168 description:
169 - The storage account access key.
170 type: str
171 state:
172 description:
173 - Assert the state of the cluster.
174 - Use C(present) to create or update a cluster and C(absent) to delete it.
175 default: present
176 type: str
177 choices:
178 - absent
179 - present
180
181 extends_documentation_fragment:
182 - azure.azcollection.azure
183 - azure.azcollection.azure_tags
184
185 author:
186 - Zim Kalinowski (@zikalino)
187
188 '''
189
190 EXAMPLES = '''
191 - name: Create instance of HDInsight Cluster
192 azure_rm_hdinsightcluster:
193 resource_group: myResourceGroup
194 name: myCluster
195 location: eastus2
196 cluster_version: 3.6
197 os_type: linux
198 tier: standard
199 cluster_definition:
200 kind: spark
201 gateway_rest_username: http-user
202 gateway_rest_password: "{{ password }}"
203 storage_accounts:
204 - name: myStorageAccount.blob.core.windows.net
205 is_default: true
206 container: myContainer
207 key: GExmaxH4lDNdHA9nwAsCt8t4AOQas2y9vXQP1kKALTram7Q3/5xLVIab3+nYG1x63Xyak9/VXxQyNBHA9pDWw==
208 compute_profile_roles:
209 - name: headnode
210 target_instance_count: 2
211 vm_size: Standard_D3
212 linux_profile:
213 username: sshuser
214 password: "{{ password }}"
215 - name: workernode
216 target_instance_count: 2
217 vm_size: Standard_D3
218 linux_profile:
219 username: sshuser
220 password: "{{ password }}"
221 '''
222
223 RETURN = '''
224 id:
225 description:
226 - Fully qualified resource id of the cluster.
227 returned: always
228 type: str
229 sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.HDInsight/clusters/myCluster
230 '''
231
232 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
233
234 try:
235 from azure.core.polling import LROPoller
236 from azure.core.exceptions import ResourceNotFoundError
237 from azure.mgmt.hdinsight import HDInsightManagementClient
238 from azure.mgmt.hdinsight.models import ClusterIdentity, UserAssignedIdentity
239 except ImportError:
240 # This is handled in azure_rm_common
241 pass
242
243
244 class Actions:
245 NoAction, Create, Update, Delete = range(4)
246
247
248 class AzureRMClusters(AzureRMModuleBaseExt):
249 """Configuration class for an Azure RM Cluster resource"""
250
251 def __init__(self):
252 self.module_arg_spec = dict(
253 resource_group=dict(
254 type='str',
255 required=True
256 ),
257 name=dict(
258 type='str',
259 required=True
260 ),
261 location=dict(
262 type='str'
263 ),
264 cluster_version=dict(
265 type='str'
266 ),
267 identity=dict(
268 type='dict',
269 options=self.managed_identity_multiple_spec
270 ),
271 os_type=dict(
272 type='str',
273 choices=['linux', 'Linux']
274 ),
275 tier=dict(
276 type='str',
277 choices=['standard',
278 'premium']
279 ),
280 cluster_definition=dict(
281 type='dict'
282 ),
283 compute_profile_roles=dict(
284 type='list',
285 elements='dict',
286 options=dict(
287 name=dict(type='str', choices=['headnode', 'workernode', 'zookeepernode']),
288 min_instance_count=dict(type='int'),
289 target_instance_count=dict(type='int'),
290 vm_size=dict(type='str'),
291 linux_profile=dict(
292 type='dict',
293 options=dict(
294 username=dict(type='str'),
295 password=dict(type='str', no_log=True)
296 )
297 ),
298 )
299 ),
300 storage_accounts=dict(
301 type='list',
302 elements='dict',
303 options=dict(
304 name=dict(type='str'),
305 is_default=dict(type='bool'),
306 container=dict(type='str'),
307 key=dict(type='str', no_log=True)
308 )
309 ),
310 state=dict(
311 type='str',
312 default='present',
313 choices=['present', 'absent']
314 )
315 )
316
317 self.resource_group = None
318 self.name = None
319 self.parameters = dict()
320
321 self.results = dict(changed=False)
322 self.mgmt_client = None
323 self.state = None
324 self.to_do = Actions.NoAction
325 self.tags_changed = False
326 self.new_instance_count = None
327 self.identity = None
328 self._managed_identity = None
329
330 super(AzureRMClusters, self).__init__(derived_arg_spec=self.module_arg_spec,
331 supports_check_mode=True,
332 supports_tags=True)
333
334 @property
335 def managed_identity(self):
336 if not self._managed_identity:
337 self._managed_identity = {"identity": ClusterIdentity,
338 "user_assigned": UserAssignedIdentity
339 }
340 return self._managed_identity
341
342 def exec_module(self, **kwargs):
343 """Main module execution method"""
344
345 for key in list(self.module_arg_spec.keys()) + ['tags']:
346 if hasattr(self, key):
347 setattr(self, key, kwargs[key])
348 elif kwargs[key] is not None:
349 self.parameters[key] = kwargs[key]
350
351 dict_expand(self.parameters, ['cluster_version'], 'properties')
352 dict_camelize(self.parameters, ['os_type'], True)
353 dict_expand(self.parameters, ['os_type'], 'properties')
354 dict_camelize(self.parameters, ['tier'], True)
355 dict_expand(self.parameters, ['tier'], 'properties')
356
357 dict_rename(self.parameters, ['cluster_definition', 'gateway_rest_username'], 'restAuthCredential.username')
358 dict_rename(self.parameters, ['cluster_definition', 'gateway_rest_password'], 'restAuthCredential.password')
359 dict_expand(self.parameters, ['cluster_definition', 'restAuthCredential.username'], 'gateway')
360 dict_expand(self.parameters, ['cluster_definition', 'restAuthCredential.password'], 'gateway')
361 dict_expand(self.parameters, ['cluster_definition', 'gateway'], 'configurations')
362
363 dict_expand(self.parameters, ['cluster_definition'], 'properties')
364 dict_expand(self.parameters, ['compute_profile_roles', 'vm_size'], 'hardware_profile')
365 dict_rename(self.parameters, ['compute_profile_roles', 'linux_profile'], 'linux_operating_system_profile')
366 dict_expand(self.parameters, ['compute_profile_roles', 'linux_operating_system_profile'], 'os_profile')
367 dict_rename(self.parameters, ['compute_profile_roles'], 'roles')
368 dict_expand(self.parameters, ['roles'], 'compute_profile')
369 dict_expand(self.parameters, ['compute_profile'], 'properties')
370 dict_rename(self.parameters, ['storage_accounts'], 'storageaccounts')
371 dict_expand(self.parameters, ['storageaccounts'], 'storage_profile')
372 dict_expand(self.parameters, ['storage_profile'], 'properties')
373
374 response = None
375
376 self.mgmt_client = self.get_mgmt_svc_client(HDInsightManagementClient,
377 base_url=self._cloud_environment.endpoints.resource_manager)
378
379 resource_group = self.get_resource_group(self.resource_group)
380
381 if "location" not in self.parameters:
382 self.parameters["location"] = resource_group.location
383
384 old_response = self.get_cluster()
385
386 curr_identity = old_response.get('identity') if old_response else None
387
388 self.parameters['identity'] = None
389 if self.identity:
390 self.update_identity, identity_result = self.update_managed_identity(curr_identity=curr_identity,
391 new_identity=self.identity)
392 self.parameters['identity'] = identity_result.as_dict()
393
394 if not old_response:
395 self.log("Cluster instance doesn't exist")
396 if self.state == 'absent':
397 self.log("Old instance didn't exist")
398 else:
399 self.to_do = Actions.Create
400 else:
401 self.log("Cluster instance already exists")
402 if self.state == 'absent':
403 self.to_do = Actions.Delete
404 elif self.state == 'present':
405 compare_result = {}
406 if (not default_compare(self.parameters, old_response, '', compare_result)):
407 if compare_result.pop('/properties/compute_profile/roles/*/target_instance_count', False):
408 # check if it's workernode
409 new_count = 0
410 old_count = 0
411 for role in self.parameters['properties']['compute_profile']['roles']:
412 if role['name'] == 'workernode':
413 new_count = role['target_instance_count']
414 for role in old_response['properties']['compute_profile']['roles']:
415 if role['name'] == 'workernode':
416 old_count = role['target_instance_count']
417 if old_count != new_count:
418 self.new_instance_count = new_count
419 self.to_do = Actions.Update
420 if compare_result.pop('/tags', False):
421 self.to_do = Actions.Update
422 self.tags_changed = True
423 if compare_result:
424 for k in compare_result.keys():
425 self.module.warn("property '" + k + "' cannot be updated (" + compare_result[k] + ")")
426 self.module.warn("only tags and target_instance_count can be updated")
427
428 if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
429 self.log("Need to Create / Update the Cluster instance")
430 self.results['changed'] = True
431 if self.check_mode:
432 return self.results
433 response = self.create_update_cluster()
434 self.log("Creation / Update done")
435 elif self.to_do == Actions.Delete:
436 self.log("Cluster instance deleted")
437 self.results['changed'] = True
438 if self.check_mode:
439 return self.results
440 self.delete_cluster()
441 else:
442 self.log("Cluster instance unchanged")
443 self.results['changed'] = False
444 response = old_response
445
446 if self.state == 'present':
447 self.results.update(self.format_item(response))
448 return self.results
449
450 def create_update_cluster(self):
451 '''
452 Creates or updates Cluster with the specified configuration.
453
454 :return: deserialized Cluster instance state dictionary
455 '''
456 self.log("Creating / Updating the Cluster instance {0}".format(self.name))
457
458 try:
459 if self.to_do == Actions.Create:
460 response = self.mgmt_client.clusters.begin_create(resource_group_name=self.resource_group,
461 cluster_name=self.name,
462 parameters=self.parameters)
463 if isinstance(response, LROPoller):
464 response = self.get_poller_result(response)
465 else:
466 if self.tags_changed:
467 response = self.mgmt_client.clusters.update(resource_group_name=self.resource_group,
468 cluster_name=self.name,
469 parameters={'tags': self.parameters.get('tags')})
470 if isinstance(response, LROPoller):
471 response = self.get_poller_result(response)
472 if self.new_instance_count:
473 response = self.mgmt_client.clusters.begin_resize(resource_group_name=self.resource_group,
474 cluster_name=self.name,
475 role_name='workernode',
476 parameters={'target_instance_count': self.new_instance_count})
477 if isinstance(response, LROPoller):
478 response = self.get_poller_result(response)
479 except Exception as exc:
480 self.fail("Error creating or updating Cluster instance: {0}".format(str(exc)))
481 return response.as_dict() if response else {}
482
483 def delete_cluster(self):
484 '''
485 Deletes specified Cluster instance in the specified subscription and resource group.
486
487 :return: True
488 '''
489 self.log("Deleting the Cluster instance {0}".format(self.name))
490 try:
491 response = self.mgmt_client.clusters.begin_delete(resource_group_name=self.resource_group,
492 cluster_name=self.name)
493 except Exception as e:
494 self.fail("Error deleting the Cluster instance: {0}".format(str(e)))
495
496 return True
497
498 def get_cluster(self):
499 '''
500 Gets the properties of the specified Cluster.
501
502 :return: deserialized Cluster instance state dictionary
503 '''
504 self.log("Checking if the Cluster instance {0} is present".format(self.name))
505 found = False
506 try:
507 response = self.mgmt_client.clusters.get(resource_group_name=self.resource_group,
508 cluster_name=self.name)
509 found = True
510 self.log("Response : {0}".format(response))
511 self.log("Cluster instance : {0} found".format(response.name))
512 except ResourceNotFoundError as e:
513 self.log('Did not find the Cluster instance.')
514 if found is True:
515 return response.as_dict()
516
517 return False
518
519 def format_item(self, d):
520 d = {
521 'id': d.get('id', None)
522 }
523 return d
524
525
526 def default_compare(new, old, path, result):
527 if new is None:
528 match = True
529 elif isinstance(new, dict):
530 match = True
531 if not isinstance(old, dict):
532 result[path] = 'old dict is null'
533 match = False
534 else:
535 for k in new.keys():
536 if not default_compare(new.get(k), old.get(k, None), path + '/' + k, result):
537 match = False
538 elif isinstance(new, list):
539 if not isinstance(old, list) or len(new) != len(old):
540 result[path] = 'length is different or null'
541 match = False
542 elif len(old) == 0:
543 match = True
544 else:
545 match = True
546 if isinstance(old[0], dict):
547 key = None
548 if 'id' in old[0] and 'id' in new[0]:
549 key = 'id'
550 elif 'name' in old[0] and 'name' in new[0]:
551 key = 'name'
552 else:
553 key = list(old[0])[0]
554 new = sorted(new, key=lambda x: x.get(key, ''))
555 old = sorted(old, key=lambda x: x.get(key, ''))
556 else:
557 new = sorted(new)
558 old = sorted(old)
559 for i in range(len(new)):
560 if not default_compare(new[i], old[i], path + '/*', result):
561 match = False
562 return match
563 else:
564 if path.endswith('password'):
565 match = True
566 else:
567 if path == '/location' or path.endswith('location_name'):
568 new = new.replace(' ', '').lower()
569 old = new.replace(' ', '').lower()
570 if new == old:
571 match = True
572 else:
573 result[path] = str(new) + ' != ' + str(old)
574 match = False
575 return match
576
577
578 def dict_camelize(d, path, camelize_first):
579 if isinstance(d, list):
580 for i in range(len(d)):
581 dict_camelize(d[i], path, camelize_first)
582 elif isinstance(d, dict):
583 if len(path) == 1:
584 old_value = d.get(path[0], None)
585 if old_value is not None:
586 d[path[0]] = _snake_to_camel(old_value, camelize_first)
587 else:
588 sd = d.get(path[0], None)
589 if sd is not None:
590 dict_camelize(sd, path[1:], camelize_first)
591
592
593 def dict_upper(d, path):
594 if isinstance(d, list):
595 for i in range(len(d)):
596 dict_upper(d[i], path)
597 elif isinstance(d, dict):
598 if len(path) == 1:
599 old_value = d.get(path[0], None)
600 if old_value is not None:
601 d[path[0]] = old_value.upper()
602 else:
603 sd = d.get(path[0], None)
604 if sd is not None:
605 dict_upper(sd, path[1:])
606
607
608 def dict_rename(d, path, new_name):
609 if isinstance(d, list):
610 for i in range(len(d)):
611 dict_rename(d[i], path, new_name)
612 elif isinstance(d, dict):
613 if len(path) == 1:
614 old_value = d.pop(path[0], None)
615 if old_value is not None:
616 d[new_name] = old_value
617 else:
618 sd = d.get(path[0], None)
619 if sd is not None:
620 dict_rename(sd, path[1:], new_name)
621
622
623 def dict_expand(d, path, outer_dict_name):
624 if isinstance(d, list):
625 for i in range(len(d)):
626 dict_expand(d[i], path, outer_dict_name)
627 elif isinstance(d, dict):
628 if len(path) == 1:
629 old_value = d.pop(path[0], None)
630 if old_value is not None:
631 d[outer_dict_name] = d.get(outer_dict_name, {})
632 d[outer_dict_name][path[0]] = old_value
633 else:
634 sd = d.get(path[0], None)
635 if sd is not None:
636 dict_expand(sd, path[1:], outer_dict_name)
637
638
639 def _snake_to_camel(snake, capitalize_first=False):
640 if capitalize_first:
641 return ''.join(x.capitalize() or '_' for x in snake.split('_'))
642 else:
643 return snake.split('_')[0] + ''.join(x.capitalize() or '_' for x in snake.split('_')[1:])
644
645
646 def main():
647 """Main execution"""
648 AzureRMClusters()
649
650
651 if __name__ == '__main__':
652 main()