Debian Codegraph @

ansible_collections/ibm/storage_virtualize/plugins/modules/ibm_svc_initial_setup.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (C) 2021 IBM CORPORATION
5 # Author(s): Shilpi Jain <[email protected]>
6 # Lavanya C R <[email protected]>
7 # Sandip Gulab Rajbanshi <[email protected]>
8 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
9
10 from __future__ import absolute_import, division, print_function
11 __metaclass__ = type
12
13 DOCUMENTATION = '''
14 ---
15 module: ibm_svc_initial_setup
16 short_description: This module allows users to manage the initial setup configuration on IBM Storage Virtualize family systems
17 version_added: "1.7.0"
18 description:
19 - Ansible interface to perform various initial system configuration
20 options:
21 clustername:
22 description:
23 - The hostname or management IP of the Storage Virtualize system.
24 required: true
25 type: str
26 domain:
27 description:
28 - Domain for the Storage Virtualize system.
29 - Valid when hostname is used for the parameter I(clustername).
30 type: str
31 username:
32 description:
33 - REST API username for the Storage Virtualize system.
34 - The parameters I(username) and I(password) are required if not using I(token) to authenticate a user.
35 type: str
36 password:
37 description:
38 - REST API password for the Storage Virtualize system.
39 - The parameters I(username) and I(password) are required if not using I(token) to authenticate a user.
40 type: str
41 token:
42 description:
43 - The authentication token to verify a user on the Storage Virtualize system.
44 - To generate a token, use the M(ibm.storage_virtualize.ibm_svc_auth) module.
45 type: str
46 log_path:
47 description:
48 - Path of debug log file.
49 type: str
50 validate_certs:
51 description:
52 - Validates certification.
53 default: false
54 type: bool
55 system_name:
56 description:
57 - Specifies system name.
58 type: str
59 dnsname:
60 description:
61 - Specifies a unique name for the system DNS server being created.
62 - Maximum two DNS servers can be configured. User needs to provide the complete list of DNS servers that are required to be configured.
63 type: list
64 elements: str
65 dnsip:
66 description:
67 - Specifies the DNS server Internet Protocol (IP) address.
68 type: list
69 elements: str
70 ntpip:
71 description:
72 - Specifies the IPv4 address or fully qualified domain name (FQDN) for the Network Time Protocol (NTP) server.
73 - To remove an already configured NTP IP, user must specify 0.0.0.0.
74 type: str
75 time:
76 description:
77 - Specifies the time to which the system must be set.
78 - This value must be in the following format MMDDHHmmYYYY (where M is month, D is day, H is hour, m is minute, and Y is year).
79 type: str
80 timezone:
81 description:
82 - Specifies the time zone to set for the system.
83 type: str
84 vdiskprotectiontime:
85 description:
86 - Specifies the volume protection time (in minutes).
87 type: int
88 version_added: 2.7.0
89 vdiskprotectionenabled:
90 description:
91 - Specifies whether the volume protection is enabled or disabled.
92 type: str
93 version_added: 2.7.0
94 choices: [ 'yes', 'no' ]
95 iscsiauthmethod:
96 description:
97 - Specify the authentication method for iSCSI communications on the system.
98 type: str
99 version_added: 2.7.0
100 choices: [ 'none', 'chap' ]
101 chapsecret:
102 description:
103 - Specify the CHAP secret to authenticate the system using iSCSI.
104 - Required when I(iscsiauthmethod=chap), to modify a CHAP secret.
105 - If I(chapsecret) is specified as an empty string (""), it is treated as nochapsecret, which clears current chapsecret.
106 type: str
107 version_added: 2.7.0
108 license_key:
109 description:
110 - Provides the license key to activate a feature that contains 16 hexadecimal characters organized in four groups
111 of four numbers with each group separated by a hyphen (such as 0123-4567-89AB-CDEF).
112 type: list
113 elements: str
114 remote:
115 description:
116 - Changes system licensing for remote-copy functions such as Metro Mirror, Global Mirror, and HyperSwap.
117 - Depending on the type of system, specify a capacity value in terabytes (TB) or specify the total number of
118 internal and external enclosures that user has licensed on the system.
119 There must be an enclosure license for all enclosures.
120 type: int
121 virtualization:
122 description:
123 - Changes system licensing for the Virtualization function.
124 - Depending on the type of system, specify a capacity value in terabytes (TB) or specify the total number of
125 storage capacity units (SCUs) that user is licensed to virtualize across tiers of storage on the system or
126 specify the number of enclosures of external storage that user is authorized to use.
127 type: int
128 compression:
129 description:
130 - Changes system licensing for the compression function.
131 - Depending on the type of system, specify a capacity value in terabytes (TB) or specify the total number of
132 storage capacity units (SCUs) that user is licensed to virtualize across tiers of storage on the system or
133 specify the total number of internal and external enclosures that user has licensed on the system.
134 type: int
135 flash:
136 description:
137 - Changes system licensing for the FlashCopy function.
138 - Depending on the type of system, specify a capacity value in terabytes (TB) or specify the total number of
139 internal and external enclosures for the FlashCopy function.
140 type: int
141 cloud:
142 description:
143 - Specifies the number of enclosures for the transparent cloud tiering function.
144 type: int
145 easytier:
146 description:
147 - Specifies the number of enclosures on which user can run Easy Tier.
148 type: int
149 physical_flash:
150 description:
151 - For physical disk licensing, this parameter enables or disables the FlashCopy function.
152 type: str
153 choices: [ 'on', 'off' ]
154 default: 'off'
155 encryption:
156 description:
157 - Specifies whether the encryption license function is enabled or disabled.
158 type: str
159 choices: [ 'on', 'off' ]
160 flashcopydefaultgrainsize:
161 description:
162 - Allow a user to change the FC grainsize to be one of either 64K or 256K.
163 type: int
164 version_added: 2.6.0
165 storageinsightscontrolaccess:
166 description:
167 - Indicates whether the storage insights control access for the system is enabled or disabled.
168 type: str
169 version_added: 2.6.0
170 choices: [ 'yes', 'no' ]
171 anomalysnapshot:
172 description:
173 - Specifies whether a volume group snapshot will be triggered in case of Ransomware Threat Detection (RTD).
174 type: str
175 version_added: 3.3.0
176 choices: [ 'on', 'off' ]
177 anomalysnapshotretentiondays:
178 description:
179 - Indicates the retention in days to be used for the volume group snapshot created in case of RTD.
180 type: int
181 version_added: 3.3.0
182 latestsnapshotextensiondays:
183 description:
184 - Specifies number of extension days to be applied to the latest valid volume group snapshot's retention in
185 case of RTD.
186 type: int
187 version_added: 3.3.0
188 author:
189 - Shilpi Jain (@Shilpi-J)
190 - Lavanya C R (@lavanyacr)
191 - Sandip Gulab Rajbanshi (@Sandip-Rajbanshi)
192 notes:
193 - This module supports C(check_mode).
194 - Error Considerations
195 - CMMVC5708E A parameter is missing a value.
196 - CMMVC5713E Some parameters are mutually exclusive.
197 - CMMVC7218E The provided license key is not valid.
198 '''
199
200 EXAMPLES = '''
201 - name: Initial configuration on FlashSystem 9200
202 ibm.storage_virtualize.ibm_svc_initial_setup:
203 clustername: "{{ clustername }}"
204 domain: "{{ domain }}"
205 username: "{{ username }}"
206 password: "{{ password }}"
207 log_path: /tmp/playbook.debug
208 system_name: cluster_test_0
209 time: 101009142021
210 timezone: 200
211 remote: 50
212 virtualization: 50
213 flash: 50
214 license_key:
215 - 0123-4567-89AB-CDEF
216 - 8921-4567-89AB-GHIJ
217 - name: Add DNS servers
218 ibm.storage_virtualize.ibm_svc_initial_setup:
219 clustername: "{{ clustername }}"
220 domain: "{{ domain }}"
221 username: "{{ username }}"
222 password: "{{ password }}"
223 log_path: /tmp/playbook.debug
224 system_name: cluster_test_
225 dnsname:
226 - dns_01
227 - dns_02
228 dnsip:
229 - '1.1.1.1'
230 - '2.2.2.2'
231 - name: Delete dns_02 server
232 ibm.storage_virtualize.ibm_svc_initial_setup:
233 clustername: "{{ clustername }}"
234 domain: "{{ domain }}"
235 username: "{{ username }}"
236 password: "{{ password }}"
237 log_path: /tmp/playbook.debug
238 system_name: cluster_test_
239 dnsname:
240 - dns_01
241 dnsip:
242 - '1.1.1.1'
243 - name: Change flashcopydefaultgrainsize to 64 and storageinsightscontrolaccess to no.
244 ibm.storage_virtualize.ibm_svc_initial_setup:
245 clustername: "{{ clustername }}"
246 username: "{{ username }}"
247 password: "{{ password }}"
248 log_path: /tmp/playbook.debug
249 flashcopydefaultgrainsize: 64
250 storageinsightscontrolaccess: "no"
251 - name: Change vdiskprotectiontime to 20 and vdiskprotectionenabled to yes.
252 ibm.storage_virtualize.ibm_svc_initial_setup:
253 clustername: "{{ clustername }}"
254 username: "{{ username }}"
255 password: "{{ password }}"
256 log_path: /tmp/playbook.debug
257 vdiskprotectiontime: 20
258 vdiskprotectionenabled: "yes"
259 - name: Change iscsiauthmethod to chap and set chapsecret.
260 ibm.storage_virtualize.ibm_svc_initial_setup:
261 clustername: "{{ clustername }}"
262 username: "{{ username }}"
263 password: "{{ password }}"
264 log_path: /tmp/playbook.debug
265 iscsiauthmethod: chap
266 chapsecret: "test_cs"
267 - name: Change iscsiauthmethod to none and clear chapsecret.
268 ibm.storage_virtualize.ibm_svc_initial_setup:
269 clustername: "{{ clustername }}"
270 username: "{{ username }}"
271 password: "{{ password }}"
272 log_path: /tmp/playbook.debug
273 iscsiauthmethod: none
274 chapsecret: ""
275 - name: Turn on anomalysnapshot, set retentiondays to 5 days and extend latest valid snapshot to 8 days.
276 ibm.storage_virtualize.ibm_svc_initial_setup:
277 clustername: "{{ clustername }}"
278 username: "{{ username }}"
279 password: "{{ password }}"
280 anomalysnapshot: 'on'
281 anomalysnapshotretentiondays: 5
282 latestsnapshotextensiondays: 8
283 '''
284
285 RETURN = '''#'''
286
287 from traceback import format_exc
288 from ansible.module_utils.basic import AnsibleModule
289 from ansible_collections.ibm.storage_virtualize.plugins.module_utils.ibm_svc_utils import IBMSVCRestApi, svc_argument_spec, get_logger
290 from ansible.module_utils._text import to_native
291
292
293 class IBMSVCInitialSetup(object):
294 def __init__(self):
295 argument_spec = svc_argument_spec()
296
297 argument_spec.update(
298 dict(
299 system_name=dict(type='str'),
300 ntpip=dict(type='str'),
301 time=dict(type='str'),
302 timezone=dict(type='str'),
303 vdiskprotectiontime=dict(type='int'),
304 vdiskprotectionenabled=dict(type='str', choices=['yes', 'no']),
305 iscsiauthmethod=dict(type='str', choices=['none', 'chap']),
306 chapsecret=dict(type='str', no_log=True),
307 flashcopydefaultgrainsize=dict(type='int'),
308 storageinsightscontrolaccess=dict(type='str', choices=['yes', 'no']),
309 dnsname=dict(type='list', elements='str'),
310 dnsip=dict(type='list', elements='str'),
311 license_key=dict(type='list', elements='str', no_log=True),
312 flash=dict(type='int'),
313 remote=dict(type='int'),
314 virtualization=dict(type='int'),
315 compression=dict(type='int'),
316 physical_flash=dict(type='str', default='off', choices=['on', 'off']),
317 easytier=dict(type='int'),
318 encryption=dict(type='str', choices=['on', 'off']),
319 cloud=dict(type='int'),
320 anomalysnapshot=dict(type='str', choices=['on', 'off']),
321 anomalysnapshotretentiondays=dict(type='int'),
322 latestsnapshotextensiondays=dict(type='int')
323 )
324 )
325
326 self.module = AnsibleModule(argument_spec=argument_spec,
327 supports_check_mode=True)
328
329 # logging setup
330 log_path = self.module.params['log_path']
331 log = get_logger(self.__class__.__name__, log_path)
332 self.log = log.info
333
334 self.changed = False
335 self.message = ""
336
337 # system related parameters
338 self.systemname = self.module.params.get('system_name', '')
339 self.ntpip = self.module.params.get('ntpip', '')
340 self.time = self.module.params.get('time', '')
341 self.timezone = self.module.params.get('timezone', '')
342 self.vdiskprotectiontime = self.module.params.get('vdiskprotectiontime', '')
343 self.vdiskprotectionenabled = self.module.params.get('vdiskprotectionenabled', '')
344 self.iscsiauthmethod = self.module.params.get('iscsiauthmethod', '')
345 self.chapsecret = self.module.params.get('chapsecret', '')
346 self.flashcopydefaultgrainsize = self.module.params.get('flashcopydefaultgrainsize', '')
347 self.storageinsightscontrolaccess = self.module.params.get('storageinsightscontrolaccess', '')
348
349 # dns related parameter
350 self.dnsname = self.module.params.get('dnsname', '')
351 self.dnsip = self.module.params.get('dnsip', '')
352
353 # license related parameters
354 self.license_key = self.module.params.get('license_key', '')
355 self.flash = self.module.params.get('flash', '')
356 self.remote = self.module.params.get('remote', '')
357 self.virtualization = self.module.params.get('virtualization', '')
358 self.compression = self.module.params.get('compression', '')
359 self.physical_flash = self.module.params.get('physical_flash', '')
360 self.easytier = self.module.params.get('easytier', '')
361 self.cloud = self.module.params.get('cloud', '')
362 self.encryption = self.module.params.get('encryption', '')
363
364 # anomalysnapshot related parameters
365 self.anomalysnapshot = self.module.params.get('anomalysnapshot', '')
366 self.anomalysnapshotretentiondays = self.module.params.get('anomalysnapshotretentiondays', '')
367 self.latestsnapshotextensiondays = self.module.params.get('latestsnapshotextensiondays', '')
368
369 self.restapi = IBMSVCRestApi(
370 module=self.module,
371 clustername=self.module.params['clustername'],
372 domain=self.module.params['domain'],
373 username=self.module.params['username'],
374 password=self.module.params['password'],
375 validate_certs=self.module.params['validate_certs'],
376 log_path=log_path,
377 token=self.module.params['token']
378 )
379
380 def basic_checks(self):
381
382 mutually_exclusive = (
383 ('time', 'ntpip'),
384 )
385 for param1, param2 in mutually_exclusive:
386 if getattr(self, param1) and getattr(self, param2):
387 self.module.fail_json(
388 msg='CMMVC5713E Mutually exclusive parameters: [{0}, {1}]'.format(param1, param2)
389 )
390
391 if self.iscsiauthmethod == "chap" and not self.chapsecret:
392 self.module.fail_json(msg='CMMVC5708E Parameter [chapsecret] is missing a value.')
393
394 if self.dnsname and self.dnsip:
395 if len(self.dnsname) != len(self.dnsip):
396 self.module.fail_json(msg='To configure DNS, number of DNS IP(s) must match the number of DNS server name(s).')
397 for dnsname, dnsip in zip(self.dnsname, self.dnsip):
398 if dnsname == "":
399 self.module.fail_json(msg='CMMVC5708E Parameter [dnsname] is missing a value.')
400 if dnsip == "":
401 self.module.fail_json(msg='CMMVC5708E Parameter [dnsip] is missing a value.')
402
403 if self.license_key:
404 for key in self.license_key:
405 if key == "":
406 self.module.fail_json(msg='CMMVC5708E Parameter [licensekey] is missing a value.')
407 if len(key) != 19: # SVC throw
408 self.module.fail_json(msg='CMMVC7218E An invalid license key was specified.')
409
410 def get_system_info(self):
411 self.log("Entering function get_system_info")
412 system_data = self.restapi.svc_obj_info(cmd='lssystem', cmdopts=None, cmdargs=None)
413 return system_data
414
415 def get_license_info(self):
416 self.log("Entering function get_license_info")
417 license_data = self.restapi.svc_obj_info(cmd='lslicense', cmdopts=None, cmdargs=None)
418 return license_data
419
420 def get_dnsserver_info(self):
421 self.log("Entering function get_dnsserver_info")
422 merged_result = []
423
424 dnsserver_data = self.restapi.svc_obj_info(cmd='lsdnsserver', cmdopts=None, cmdargs=None)
425
426 if isinstance(dnsserver_data, list):
427 for d in dnsserver_data:
428 merged_result.append(d)
429 else:
430 merged_result = dnsserver_data
431
432 return merged_result
433
434 def get_feature_info(self):
435 self.log("Entering function get_feature_info")
436 feature_data = self.restapi.svc_obj_info('lsfeature', cmdopts=None, cmdargs=None)
437 return feature_data
438
439 def system_probe(self, data):
440 props = []
441
442 field_mappings = (
443 ('systemname', data.get('name', '')),
444 ('ntpip', data.get('cluster_ntp_IP_address', '')),
445 ('vdiskprotectiontime', int(data.get('vdisk_protection_time', 0))),
446 ('vdiskprotectionenabled', data.get('vdisk_protection_enabled', '')),
447 ('iscsiauthmethod', data.get('iscsi_auth_method', '')),
448 ('flashcopydefaultgrainsize', int(data.get('flashcopy_default_grainsize', 0))),
449 ('storageinsightscontrolaccess', data.get('storage_insights_control_access', '')),
450 )
451
452 for field, existing_value in field_mappings:
453 new_value = getattr(self, field, None)
454 if new_value is not None and new_value != existing_value:
455 props.append(field)
456
457 if self.chapsecret is not None:
458 if self.chapsecret != "" and self.chapsecret != data['iscsi_chap_secret']:
459 props.append('chapsecret')
460 elif self.chapsecret == "" and data['iscsi_chap_secret'] != "":
461 self.nochapsecret = True
462 props.append('nochapsecret')
463
464 if self.time and data['cluster_ntp_IP_address'] != "":
465 props.append('ntpip')
466
467 if self.time:
468 props.append('time')
469
470 if self.timezone and (self.timezone != (data['time_zone'].split(" ", 1)[0] if data['time_zone'] else None)):
471 props.append('timezone')
472
473 self.log("system_probe props='%s'", props)
474 return props
475
476 def systemtime_update(self):
477 cmd = 'setsystemtime'
478 cmdopts = {}
479 cmdopts['time'] = self.time
480
481 self.restapi.svc_run_command(cmd, cmdopts, cmdargs=None)
482 self.log("Properties: Time %s updated", self.time)
483
484 def timezone_update(self):
485 cmd = 'settimezone'
486 cmdopts = {}
487 cmdopts['timezone'] = self.timezone
488
489 self.restapi.svc_run_command(cmd, cmdopts, cmdargs=None)
490 self.log("Properties: Time zone %s updated", self.timezone)
491
492 def system_update(self, modify, data):
493
494 self.log("updating system '%s'", self.systemname)
495 if self.module.check_mode:
496 self.changed = True
497 return
498
499 cmd = 'chsystem'
500 cmdopts = {}
501
502 system_name_required = False
503 time_change_required = False
504
505 if 'systemname' in modify:
506 cmdopts['name'] = self.systemname
507 system_name_required = True
508 modify.remove('systemname')
509
510 if 'ntpip' in modify:
511 cmdopts['ntpip'] = self.ntpip if self.ntpip else '0.0.0.0'
512 modify.remove('ntpip')
513
514 if 'time' in modify:
515 time_change_required = True
516 modify.remove('time')
517
518 if 'timezone' in modify:
519 self.timezone_update()
520 self.changed = True
521 modify.remove('timezone')
522
523 for param in modify:
524 cmdopts[param] = getattr(self, param)
525
526 if 'iscsiauthmethod' in modify and self.iscsiauthmethod == 'chap':
527 cmdopts['chapsecret'] = self.chapsecret if 'chapsecret' in modify else data['iscsi_chap_secret']
528
529 cmdoptsList = cmdopts.keys()
530 if cmdopts:
531 self.restapi.svc_run_command(cmd, cmdopts, cmdargs=None)
532 self.changed = True
533 self.log("Properties updated: %s", cmdoptsList)
534
535 if time_change_required:
536 self.systemtime_update()
537 self.changed = True
538
539 if cmdopts:
540 if system_name_required:
541 self.message += "System [{0}] has been successfully renamed to [{1}]{2}".format(
542 data['name'],
543 self.systemname,
544 ' and other parameters updated.' if (len(cmdoptsList) > 1) else '.'
545 )
546 else:
547 self.message += "System %s updated" % data['name']
548
549 def dns_configure(self, data):
550 existing_dns = {}
551 existing_dns_server = []
552 existing_dns_ip = []
553
554 if self.module.check_mode:
555 self.changed = True
556 return
557
558 if self.dnsip and self.dnsname:
559 for server in data:
560 existing_dns_server.append(server['name'])
561 existing_dns_ip.append(server['IP_address'])
562 existing_dns[server['name']] = server['IP_address']
563
564 for name, ip in zip(self.dnsname, self.dnsip): # To modify existing name or ip
565 if name in existing_dns and existing_dns[name] != ip:
566 self.log("update, diff IP.")
567 self.restapi.svc_run_command(
568 'chdnsserver', {'ip': ip}, [name]
569 )
570 self.changed = True
571 self.message += "DNS %s modified." % name
572
573 if (set(existing_dns_server)).symmetric_difference(set(self.dnsname)):
574
575 dnsserver_to_remove = list(set(existing_dns_server) - set(self.dnsname))
576 if dnsserver_to_remove:
577 for item in dnsserver_to_remove:
578 self.restapi.svc_run_command(
579 'rmdnsserver', None,
580 [item]
581 )
582 self.message += " DNS server %s removed." % dnsserver_to_remove
583
584 dnsservername_to_add = list(set(self.dnsname) - set(existing_dns_server))
585 dnsserverid_to_add = list(set(self.dnsip) - set(existing_dns_ip))
586 if dnsservername_to_add:
587 for dns_name, dns_ip in zip(dnsservername_to_add, dnsserverid_to_add):
588 self.log('%s %s', dns_name, dns_ip)
589 self.restapi.svc_run_command(
590 'mkdnsserver',
591 {'name': dns_name, 'ip': dns_ip}, cmdargs=None
592 )
593 self.message += " DNS server %s added." % dnsservername_to_add
594 self.changed = True
595
596 def license_probe(self, data, sys_data):
597 props = []
598
599 field_mappings = (
600 ('flash', int(data.get('license_flash', 0))),
601 ('remote', int(data.get('license_remote', 0))),
602 ('virtualization', int(data.get('license_virtualization', 0))),
603 ('physical_flash', data.get('license_physical_flash', '')),
604 ('easytier', int(data.get('license_easy_tier', 0))),
605 ('cloud', int(data.get('license_cloud_enclosures', 0))),
606 )
607
608 for field, existing_value in field_mappings:
609 new_value = getattr(self, field, None)
610 if new_value is not None and new_value != existing_value:
611 props.append(field)
612
613 if self.compression:
614 if (sys_data['product_name'] == "IBM Storwize V7000") or (sys_data['product_name'] == "IBM FlashSystem 7200"):
615 if (int(data['license_compression_enclosures']) != self.compression):
616 self.log("license_compression_enclosure=%d", int(data['license_compression_enclosures']))
617 props.append('compression')
618 else:
619 if (int(data['license_compression_capacity']) != self.compression):
620 self.log("license_compression_capacity=%d", int(data['license_compression_capacity']))
621 props.append('compression')
622
623 self.log("license_probe props: %s", props)
624 return props
625
626 def license_update(self, modify):
627 self.log("updating license of '%s'", self.systemname)
628 if self.module.check_mode:
629 self.changed = True
630 return
631
632 for license in modify:
633 cmdopts = {}
634 cmdopts[license] = getattr(self, license)
635 self.restapi.svc_run_command('chlicense', cmdopts, cmdargs=None)
636
637 if self.encryption:
638 self.restapi.svc_run_command('chlicense', {'encryption': self.encryption}, cmdargs=None)
639
640 self.changed = True
641 self.log("Licensed functions %s updated", modify)
642 self.message += " Licensed functions %s updated." % modify
643
644 def license_key_update(self, data):
645 existing_license_keys = []
646 existing_license_id_pairs = {}
647
648 if self.module.check_mode:
649 self.changed = True
650 return
651
652 for feature in data:
653 existing_license_keys.append(feature['license_key'])
654 existing_license_id_pairs[feature['license_key']] = feature['id']
655 self.log("existing licenses=%s, license_id_pairs=%s", existing_license_keys, existing_license_id_pairs)
656
657 if (set(existing_license_keys)).symmetric_difference(set(self.license_key)):
658 activate_license_keys = list(set(self.license_key) - set(existing_license_keys))
659 deactivate_license_keys = list(set(existing_license_keys) - set(self.license_key))
660
661 if deactivate_license_keys:
662 for key in deactivate_license_keys:
663 if key:
664 self.restapi.svc_run_command(
665 'deactivatefeature', None, [existing_license_id_pairs[key]]
666 )
667 self.changed = True
668 self.log('%s deactivated', deactivate_license_keys)
669 self.message += " License %s deactivated." % deactivate_license_keys
670
671 if activate_license_keys:
672 for key in activate_license_keys:
673 if key:
674 self.restapi.svc_run_command(
675 'activatefeature', {'licensekey': key}, None
676 )
677 self.changed = True
678 self.log('%s activated', key)
679 self.message += " License %s activated." % activate_license_keys
680 else:
681 self.message += " No license Changes."
682
683 def anomaly_setup(self):
684 cmdopts = {}
685 if self.anomalysnapshot:
686 cmdopts['anomalysnapshot'] = self.anomalysnapshot
687 if self.anomalysnapshotretentiondays:
688 cmdopts['anomalysnapshotretentiondays'] = self.anomalysnapshotretentiondays
689 if self.latestsnapshotextensiondays:
690 cmdopts['latestsnapshotextensiondays'] = self.latestsnapshotextensiondays
691
692 if self.module.check_mode:
693 self.changed = True
694 return
695
696 self.restapi.svc_run_command(
697 'chanomalydetection', cmdopts, None)
698 self.changed = True
699 self.log("Anomaly snapshot configuration updated: %s", cmdopts)
700 self.message += " Anomaly snapshot configuration updated."
701
702 def apply(self):
703 msg = None
704 modify = []
705
706 self.basic_checks()
707
708 # System Configuration
709 system_data = self.get_system_info()
710 modify = self.system_probe(system_data)
711 if modify:
712 self.system_update(modify, system_data)
713
714 # DNS configuration
715 if self.dnsname and self.dnsip:
716 dns_data = self.get_dnsserver_info()
717 self.dns_configure(dns_data)
718
719 # For honour based licenses
720 license_data = self.get_license_info()
721 modify = self.license_probe(license_data, system_data)
722 if modify:
723 self.license_update(modify)
724
725 # For key based licenses
726 if self.license_key:
727 feature_data = self.get_feature_info()
728 self.license_key_update(feature_data)
729
730 # For anomaly snapshot configuration
731 if self.anomalysnapshot or self.anomalysnapshotretentiondays or self.latestsnapshotextensiondays:
732 self.anomaly_setup()
733
734 if self.changed:
735 if self.module.check_mode:
736 msg = "skipping changes due to check mode."
737 else:
738 msg = self.message
739 else:
740 msg = "No modifications required. Exiting with no changes."
741
742 self.module.exit_json(msg=msg, changed=self.changed)
743
744
745 def main():
746 v = IBMSVCInitialSetup()
747 try:
748 v.apply()
749 except Exception as e:
750 v.log("Exception in apply(): \n%s", format_exc())
751 v.module.fail_json(msg="Module failed. Error [%s]." % to_native(e))
752
753
754 if __name__ == '__main__':
755 main()