Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2024 xuzhang3 (@xuzhang3), Fred-sun (@Fred-sun)
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_mysqlflexibleserver
14 version_added: "2.7.0"
15 short_description: Manage MySQL Flexible Server instance
16 description:
17 - Create, update and delete instance of MySQL Flexible Server.
18
19 options:
20 resource_group:
21 description:
22 - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
23 required: True
24 type: str
25 name:
26 description:
27 - The name of the server.
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 sku:
35 description:
36 - The SKU (pricing tier) of the server.
37 type: dict
38 suboptions:
39 name:
40 description:
41 - The name of the sku, e.g. Standard_D32s_v3.
42 type: str
43 required: true
44 tier:
45 description:
46 - The tier of the particular SKU,
47 type: str
48 choices:
49 - Burstable
50 - GeneralPurpose
51 - MemoryOptimized
52 required: true
53 storage:
54 description:
55 - Storage Profile properties of a server.
56 type: dict
57 suboptions:
58 storage_size_gb:
59 description:
60 - Max storage size allowed for a server.
61 type: int
62 iops:
63 description:
64 - Storage IOPS for a server.
65 type: int
66 auto_grow:
67 description:
68 - Enable Storage Auto Grow or not.
69 type: str
70 choices:
71 - Disabled
72 - Enabled
73 version:
74 description:
75 - Server version.
76 type: str
77 choices:
78 - '5.7'
79 - '8.0.21'
80 administrator_login:
81 description:
82 - The administrator's login name of a server.
83 - Can only be specified when the server is being created (and is required for creation).
84 type: str
85 administrator_login_password:
86 description:
87 - The password of the administrator login.
88 type: str
89 availability_zone:
90 description:
91 - Availability Zone information of the server.
92 type: str
93 restore_point_in_time:
94 description:
95 - Restore point creation time (ISO8601 format), specifying the time to restore from.
96 - Required when C(source_server_resource_id) is specified.
97 type: str
98 source_server_resource_id:
99 description:
100 - The source MySQL server id.
101 - Required when C(restore_point_in_time) is specified.
102 type: str
103 backup:
104 description:
105 - Backup related properties of a server.
106 type: dict
107 suboptions:
108 geo_redundant_backup:
109 description:
110 - Whether or not geo redundant backup is enabled.
111 type: str
112 choices:
113 - Enabled
114 - Disabled
115 backup_retention_days:
116 description:
117 - Backup retention days for the server.
118 type: int
119 network:
120 description:
121 - Network related properties of a server.
122 type: dict
123 suboptions:
124 delegated_subnet_resource_id:
125 description:
126 - Delegated subnet resource id used to setup vnet for a server.
127 type: str
128 private_dns_zone_resource_id:
129 description:
130 - Private DNS zone resource id.
131 type: str
132 high_availability:
133 description:
134 - High availability related properties of a server.
135 type: dict
136 suboptions:
137 mode:
138 description:
139 - High availability mode for a server.
140 type: str
141 choices:
142 - Disabled
143 - ZoneRedundant
144 - SameZone
145 standby_availability_zone:
146 description:
147 - Vailability zone of the standby server.
148 type: str
149 status:
150 description:
151 Set the server state.
152 type: str
153 choices:
154 - restart
155 - start
156 - stop
157 - failover
158 state:
159 description:
160 - Assert the state of the MySQL Flexible Server. Use C(present) to create or update a server and C(absent) to delete it.
161 default: present
162 type: str
163 choices:
164 - absent
165 - present
166
167 extends_documentation_fragment:
168 - azure.azcollection.azure
169 - azure.azcollection.azure_tags
170
171 author:
172 - xuzhang3 (@xuzhang3)
173 - Fred-sun (@Fred-sun)
174
175 '''
176
177 EXAMPLES = '''
178 - name: Create mysql flexible server
179 azure_rm_mysqlflexibleserver:
180 resource_group: "{{ resource_group }}"
181 name: postflexible{{ rpfx }}
182 sku:
183 name: Standard_D2ds_v4
184 tier: GeneralPurpose
185 administrator_login: azureuser
186 administrator_login_password: Fred@0329
187 location: northeurope
188 version: 5.7
189 storage:
190 storage_size_gb: 128
191 iops: 500
192 auto_grow: Enabled
193 high_availability:
194 mode: ZoneRedundant
195 standby_availability_zone: 3
196 backup:
197 backup_retention_days: 7
198 geo_redundant_backup: Disabled
199 availability_zone: 1
200
201 - name: Restore MySQL flexible server from a point-in-time backup
202 azure_rm_mysqlflexibleserver:
203 resource_group: "{{ resource_group }}"
204 name: postflexible-restore{{ rpfx }}
205 source_server_resource_id: "{{ mysql_flexible_server_id }}"
206 restore_point_in_time: "2026-02-26T02:27:14Z"
207 '''
208
209 RETURN = '''
210 servers:
211 description:
212 - The facts of the flexible servers.
213 returned: always
214 type: complex
215 contains:
216 id:
217 description:
218 - Resource ID.
219 returned: always
220 type: str
221 sample: /subscriptions/xxxx-xxxx/resourceGroups/testRG/providers/Microsoft.DBforMySQL/flexibleServers/server01
222 resource_group:
223 description:
224 - Resource group name.
225 returned: always
226 type: str
227 sample: testRG
228 name:
229 description:
230 - Resource name.
231 returned: always
232 type: str
233 sample: server01
234 location:
235 description:
236 - The location the resource resides in.
237 returned: always
238 type: str
239 sample: eastus
240 sku:
241 description:
242 - The SKU of the server.
243 returned: always
244 type: complex
245 contains:
246 name:
247 description:
248 - The name of the SKU.
249 returned: always
250 type: str
251 sample: Standard_D32s_v3
252 tier:
253 description:
254 - The tier of the particular SKU.
255 returned: always
256 type: str
257 sample: GeneralPurpose
258 storage:
259 description:
260 - Storage related properties of a server.
261 type: complex
262 returned: always
263 contains:
264 storage_size_gb:
265 description:
266 - Max storage size allowed for a server.
267 returned: always
268 type: int
269 sample: 128000
270 iops:
271 description:
272 - Storage IOPS for a server.
273 returned: always
274 type: int
275 sample: 684
276 auto_grow:
277 description:
278 - Enable Storage Auto Grow or not.
279 returned: always
280 type: str
281 sample: Disabled
282 availability_zone:
283 description:
284 - Availability Zone information of the server.
285 returned: always
286 type: str
287 sample: 1
288 administrator_login_password:
289 description:
290 - The administrator's login name of a server.
291 returned: always
292 type: str
293 sample: serveradmin
294 backup:
295 description:
296 - Backup related properties of a server.
297 type: complex
298 contains:
299 backup_retention_days:
300 description:
301 - Backup retention days for the server.
302 type: int
303 returned: always
304 sample: 7
305 geo_redundant_backup:
306 description:
307 - Whether or not geo redundant backup is enabled.
308 type: str
309 returned: always
310 sample: Disabled
311 version:
312 description:
313 - Server version.
314 returned: always
315 type: str
316 sample: "5.7"
317 status:
318 description:
319 - Set server state.
320 type: str
321 choices:
322 - restart
323 - start
324 - stop
325 - failover
326 state:
327 description:
328 - A state of a server that is visible to user.
329 returned: always
330 type: str
331 sample: Ready
332 fully_qualified_domain_name:
333 description:
334 - The fully qualified domain name of a server.
335 returned: always
336 type: str
337 sample: myabdud1223.mys.database.azure.com
338 high_availability:
339 description:
340 - High availability related properties of a server.
341 type: complex
342 returned: always
343 contains:
344 mode:
345 description:
346 - High availability mode for a server.
347 type: str
348 sample: Disabled
349 returned: always
350 standby_availability_zone:
351 description:
352 - Availability zone of the standby server.
353 type: str
354 sample: Availability zone of the standby server.
355 returned: always
356 network:
357 description:
358 - Network related properties of a server.
359 type: complex
360 returned: always
361 contains:
362 delegated_subnet_resource_id:
363 description:
364 - Delegated subnet resource id used to setup vnet for a server.
365 type: str
366 sample: null
367 returned: always
368 private_dns_zone_resource_id:
369 description:
370 - Private DNS zone resource id.
371 type: str
372 sample: null
373 returned: always
374 restore_point_in_time:
375 description:
376 - Restore point creation time (ISO8601 format), specifying the time to restore from.
377 type: str
378 returned: always
379 sample: null
380 source_server_resource_id:
381 description:
382 - The source MySQL server id.
383 type: str
384 returned: always
385 sample: null
386 tags:
387 description:
388 - Tags assigned to the resource. Dictionary of string:string pairs.
389 type: dict
390 returned: always
391 sample: { tag1: abc }
392 type:
393 description:
394 - The type of the resource.
395 type: str
396 returned: always
397 sample: Microsoft.DBforMySQL/flexibleServers
398 '''
399
400
401 try:
402 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
403 from azure.core.exceptions import ResourceNotFoundError
404 from azure.core.polling import LROPoller
405 except ImportError:
406 # This is handled in azure_rm_common
407 pass
408
409 storage_spec = dict(
410 storage_size_gb=dict(
411 type='int'
412 ),
413 iops=dict(
414 type='int'
415 ),
416 auto_grow=dict(
417 type='str',
418 choices=['Disabled', 'Enabled']
419 )
420 )
421
422
423 high_availability_spec = dict(
424 mode=dict(type='str', choices=["Disabled", "ZoneRedundant", "SameZone"]),
425 standby_availability_zone=dict(type='str')
426 )
427
428
429 sku_spec = dict(
430 name=dict(type='str', required=True),
431 tier=dict(type='str', required=True, choices=["Burstable", "GeneralPurpose", "MemoryOptimized"])
432 )
433
434
435 backup_spec = dict(
436 backup_retention_days=dict(type='int'),
437 geo_redundant_backup=dict(type='str', choices=["Enabled", "Disabled"])
438 )
439
440
441 network_spec = dict(
442 delegated_subnet_resource_id=dict(type='str'),
443 private_dns_zone_resource_id=dict(type='str'),
444 )
445
446
447 class Actions:
448 NoAction, Create, Update, Delete = range(4)
449
450
451 class AzureRMMySqlFlexibleServers(AzureRMModuleBaseExt):
452 """Configuration class for an Azure RM MySQL Flexible Server resource"""
453
454 def __init__(self):
455 self.module_arg_spec = dict(
456 resource_group=dict(
457 type='str',
458 required=True
459 ),
460 name=dict(
461 type='str',
462 required=True
463 ),
464 sku=dict(
465 type='dict',
466 options=sku_spec
467 ),
468 location=dict(
469 type='str'
470 ),
471 version=dict(
472 type='str',
473 choices=['5.7', '8.0.21']
474 ),
475 administrator_login=dict(
476 type='str'
477 ),
478 administrator_login_password=dict(
479 type='str',
480 no_log=True
481 ),
482 availability_zone=dict(
483 type='str'
484 ),
485 restore_point_in_time=dict(
486 type='str'
487 ),
488 source_server_resource_id=dict(
489 type='str'
490 ),
491 backup=dict(
492 type='dict',
493 options=backup_spec
494 ),
495 network=dict(
496 type='dict',
497 options=network_spec
498 ),
499 storage=dict(
500 type='dict',
501 options=storage_spec
502 ),
503 high_availability=dict(
504 type='dict',
505 options=high_availability_spec
506 ),
507 status=dict(
508 type='str',
509 choices=['restart', 'start', 'stop', 'failover']
510 ),
511 state=dict(
512 type='str',
513 default='present',
514 choices=['present', 'absent']
515 )
516 )
517
518 self.resource_group = None
519 self.name = None
520 self.parameters = dict()
521 self.update_parameters = dict()
522 self.status = None
523 self.tags = None
524
525 self.results = dict(changed=False)
526 self.state = None
527 self.to_do = Actions.NoAction
528
529 required_together = [['restore_point_in_time', 'source_server_resource_id']]
530
531 super(AzureRMMySqlFlexibleServers, self).__init__(derived_arg_spec=self.module_arg_spec,
532 supports_check_mode=True,
533 required_together=required_together,
534 supports_tags=True)
535
536 def exec_module(self, **kwargs):
537 """Main module execution method"""
538
539 for key in list(self.module_arg_spec.keys()) + ['tags']:
540 if hasattr(self, key):
541 setattr(self, key, kwargs[key])
542 elif kwargs[key] is not None:
543 if key == "sku":
544 self.parameters["sku"] = kwargs[key]
545 self.update_parameters["sku"] = kwargs[key]
546 elif key == "location":
547 self.parameters["location"] = kwargs[key]
548 elif key == "storage":
549 self.parameters["storage"] = kwargs[key]
550 self.update_parameters["storage"] = kwargs[key]
551 elif key == "version":
552 self.parameters["version"] = kwargs[key]
553 elif key == "administrator_login":
554 self.parameters["administrator_login"] = kwargs[key]
555 elif key == "administrator_login_password":
556 self.parameters["administrator_login_password"] = kwargs[key]
557 elif key == 'availability_zone':
558 self.parameters['availability_zone'] = kwargs[key]
559 elif key == 'source_server_resource_id':
560 self.parameters['source_server_resource_id'] = kwargs[key]
561 elif key == 'restore_point_in_time':
562 self.parameters['restore_point_in_time'] = kwargs[key]
563 elif key == 'backup':
564 self.parameters['backup'] = kwargs[key]
565 self.update_parameters['backup'] = kwargs[key]
566 elif key == 'high_availability':
567 self.parameters['high_availability'] = kwargs[key]
568 self.update_parameters['high_availability'] = kwargs[key]
569 elif key == 'network':
570 self.parameters['network'] = kwargs[key]
571
572 self.parameters['tags'] = self.tags
573
574 # If this is a PointInTimeRestore, set create_mode to PointInTimeRestore
575 if self.parameters.get('source_server_resource_id') and self.parameters.get('restore_point_in_time'):
576 self.parameters['create_mode'] = 'PointInTimeRestore'
577
578 old_response = None
579 response = None
580 changed = False
581
582 resource_group = self.get_resource_group(self.resource_group)
583 if "location" not in self.parameters:
584 self.parameters["location"] = resource_group.location
585
586 old_response = self.get_mysqlserver()
587
588 if not old_response:
589 if self.state == 'absent':
590 self.log("The mysql flexible server didn't exist")
591 else:
592 changed = True
593 self.to_do = Actions.Create
594 else:
595 self.log("MySQL Flexible Server instance already exists")
596 if self.state == 'absent':
597 changed = True
598 self.to_do = Actions.Delete
599 else:
600 self.log("Whether the MySQL Flexible Server instance need update")
601 update_tags, self.update_parameters['tags'] = self.update_tags(old_response.get('tags'))
602 if update_tags:
603 changed = True
604 self.to_do = Actions.Update
605
606 for item in ['sku', 'network', 'storage', 'backup', 'high_availability']:
607 if not self.default_compare({}, self.update_parameters.get(item), old_response[item], '', dict(compare=[])):
608 changed = True
609 self.to_do = Actions.Update
610
611 if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
612 self.log("Need to Create / Update the MySQL Flexible Server instance")
613
614 if not self.check_mode:
615 response = self.create_update_mysqlserver()
616 self.log("Creation / Update done")
617 elif self.to_do == Actions.Delete:
618 self.log("MySQL Flexible Server instance deleted")
619 if not self.check_mode:
620 self.delete_mysqlserver()
621 if self.status is not None:
622 if self.status == 'start':
623 self.start_mysqlserver()
624 changed = True
625 elif self.status == 'restart':
626 self.restart_mysqlserver()
627 changed = True
628 elif self.status == 'stop':
629 self.stop_mysqlserver()
630 changed = True
631 elif self.status == 'failover':
632 self.failover_mysqlserver()
633 changed = True
634 else:
635 pass
636 self.results['changed'] = changed
637 self.results['state'] = self.get_mysqlserver()
638 return self.results
639
640 def failover_mysqlserver(self):
641 '''
642 Manual failover MySQL Flexible Server.
643 '''
644 self.log("Failover MySQL Flexible Server instance {0}".format(self.name))
645
646 try:
647 response = self.mysql_flexible_client.servers.begin_failover(resource_group_name=self.resource_group,
648 server_name=self.name)
649 except Exception as exc:
650 self.fail("Error failover mysql flexible server {0} - {1}".format(self.name, str(exc)))
651 return True
652
653 def stop_mysqlserver(self):
654 '''
655 Stop MySQL Flexible Server.
656 '''
657 self.log("Stop MySQL Flexible Server instance {0}".format(self.name))
658
659 try:
660 response = self.mysql_flexible_client.servers.begin_stop(resource_group_name=self.resource_group,
661 server_name=self.name)
662 except Exception as exc:
663 self.fail("Error stop mysql flexible server {0} - {1}".format(self.name, str(exc)))
664 return True
665
666 def start_mysqlserver(self):
667 '''
668 Start MySQL Flexible Server.
669 '''
670 self.log("Start MySQL Flexible Server instance {0}".format(self.name))
671
672 try:
673 response = self.mysql_flexible_client.servers.begin_start(resource_group_name=self.resource_group,
674 server_name=self.name)
675 except Exception as exc:
676 self.fail("Error starting mysql flexible server {0} - {1}".format(self.name, str(exc)))
677 return True
678
679 def restart_mysqlserver(self):
680 '''
681 Restart MySQL Flexible Server.
682 '''
683 self.log("Restart MySQL Flexible Server instance {0}".format(self.name))
684
685 try:
686 response = self.mysql_flexible_client.servers.begin_restart(resource_group_name=self.resource_group,
687 server_name=self.name,
688 parameters=dict(restart_with_failover='Enabled',
689 max_failover_seconds=20))
690 except Exception as exc:
691 self.fail("Error restarting mysql flexible server {0} - {1}".format(self.name, str(exc)))
692 return True
693
694 def create_update_mysqlserver(self):
695 '''
696 Creates or updates MySQL Flexible Server with the specified configuration.
697
698 :return: deserialized MySQL Flexible Server instance state dictionary
699 '''
700 self.log("Creating / Updating the MySQL Flexible Server instance {0}".format(self.name))
701
702 try:
703 self.parameters['tags'] = self.tags
704 if self.to_do == Actions.Create:
705 response = self.mysql_flexible_client.servers.begin_create(resource_group_name=self.resource_group,
706 server_name=self.name,
707 parameters=self.parameters)
708 else:
709 # structure of parameters for update must be changed
710 response = self.mysql_flexible_client.servers.begin_update(resource_group_name=self.resource_group,
711 server_name=self.name,
712 parameters=self.update_parameters)
713 if isinstance(response, LROPoller):
714 response = self.get_poller_result(response)
715
716 except Exception as exc:
717 self.log('Error attempting to create the MySQL Flexible Server instance.')
718 self.fail("Error creating the MySQL Flexible Server instance: {0}".format(str(exc)))
719 return self.format_item(response)
720
721 def delete_mysqlserver(self):
722 '''
723 Deletes specified MySQL Flexible Server instance in the specified subscription and resource group.
724
725 :return: True
726 '''
727 self.log("Deleting the MySQL Flexible Server instance {0}".format(self.name))
728 try:
729 response = self.mysql_flexible_client.servers.begin_delete(resource_group_name=self.resource_group,
730 server_name=self.name)
731 except Exception as e:
732 self.log('Error attempting to delete the MySQL Flexible Server instance.')
733 self.fail("Error deleting the MySQL Flexible Server instance: {0}".format(str(e)))
734
735 return True
736
737 def get_mysqlserver(self):
738 '''
739 Gets the properties of the specified MySQL Flexible Server.
740
741 :return: deserialized MySQL Flexible Server instance state dictionary
742 '''
743 self.log("Checking if the MySQL Flexible Server instance {0} is present".format(self.name))
744 found = False
745 try:
746 response = self.mysql_flexible_client.servers.get(resource_group_name=self.resource_group,
747 server_name=self.name)
748 found = True
749 self.log("Response : {0}".format(response))
750 self.log("MySQL Flexible Server instance : {0} found".format(response.name))
751 except ResourceNotFoundError as e:
752 self.log('Did not find the MySQL Flexible Server instance.')
753 if found is True:
754 return self.format_item(response)
755
756 return False
757
758 def format_item(self, item):
759 results = dict(
760 resource_group=self.parse_resource_to_dict(item.id).get('resource_group'),
761 id=item.id,
762 name=item.name,
763 type=item.type,
764 tags=item.tags,
765 location=item.location,
766 sku=dict(),
767 administrator_login=item.administrator_login,
768 version=item.version,
769 availability_zone=item.availability_zone,
770 source_server_resource_id=item.source_server_resource_id,
771 restore_point_in_time=item.restore_point_in_time,
772 state=item.state,
773 fully_qualified_domain_name=item.fully_qualified_domain_name,
774 storage=dict(),
775 backup=dict(),
776 high_availability=dict(),
777 network=dict(),
778 )
779 if item.sku not in [None, 'None']:
780 results['sku']['name'] = item.sku.name
781 results['sku']['tier'] = item.sku.tier
782 else:
783 results['sku'] = None
784 if item.storage not in [None, 'None']:
785 results['storage']['storage_size_gb'] = item.storage.storage_size_gb
786 results['storage']['iops'] = item.storage.iops
787 results['storage']['auto_grow'] = item.storage.auto_grow
788 else:
789 results['storage'] = None
790 if item.high_availability not in [None, 'None']:
791 results['high_availability']['standby_availability_zone'] = item.high_availability.standby_availability_zone
792 results['high_availability']['mode'] = item.high_availability.mode
793 else:
794 results['high_availability'] = None
795 if item.backup not in [None, 'None']:
796 results['backup']['backup_retention_days'] = item.backup.backup_retention_days
797 results['backup']['geo_redundant_backup'] = item.backup.geo_redundant_backup
798 else:
799 results['backup'] = None
800 if item.network not in [None, 'None']:
801 results['network']['delegated_subnet_resource_id'] = item.network.delegated_subnet_resource_id
802 results['network']['private_dns_zone_resource_id'] = item.network.private_dns_zone_resource_id
803 else:
804 results['network'] = None
805 return results
806
807
808 def main():
809 """Main execution"""
810 AzureRMMySqlFlexibleServers()
811
812
813 if __name__ == '__main__':
814 main()