Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2017 Zim Kalinowski, <[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_sqldatabase
14 version_added: "0.1.2"
15 short_description: Manage SQL Database instance
16 description:
17 - Create, update and delete instance of SQL Database.
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 server_name:
26 description:
27 - The name of the server.
28 required: True
29 type: str
30 name:
31 description:
32 - The name of the database to be operated on (updated or created).
33 required: True
34 type: str
35 location:
36 description:
37 - Resource location. If not set, location from the resource group will be used as default.
38 type: str
39 collation:
40 description:
41 - The collation of the database. If not I(create_mode=default), this value is ignored.
42 type: str
43 create_mode:
44 description:
45 - Specifies the mode of database creation.
46 - C(default), regular database creation.
47 - C(copy), creates a database as a copy of an existing database.
48 - C(online_secondary)/C(non_readable_secondary), creates a database as a (readable or nonreadable) secondary replica of an existing database.
49 - C(point_in_time_restore), Creates a database by restoring a point in time backup of an existing database.
50 - C(recovery), Creates a database by restoring a geo-replicated backup.
51 - C(restore), Creates a database by restoring a backup of a deleted database.
52 - C(restore_long_term_retention_backup), Creates a database by restoring from a long term retention vault.
53 - C(copy), C(non_readable_secondary), C(online_secondary) and C(restore_long_term_retention_backup) are not supported for C(data_warehouse) edition.
54 type: str
55 choices:
56 - 'copy'
57 - 'default'
58 - 'non_readable_secondary'
59 - 'online_secondary'
60 - 'point_in_time_restore'
61 - 'recovery'
62 - 'restore'
63 - 'restore_long_term_retention_backup'
64 source_database_id:
65 description:
66 - Required unless I(create_mode=default) or I(create_mode=restore_long_term_retention_backup).
67 - Specifies the resource ID of the source database.
68 type: str
69 source_database_deletion_date:
70 description:
71 - Required if I(create_mode=restore) and I(source_database_id) is the deleted database's original resource id when it existed (as
72 opposed to its current restorable dropped database ID), then this value is required. Specifies the time that the database was deleted.
73 type: str
74 restore_point_in_time:
75 description:
76 - Required if I(create_mode=point_in_time_restore), this value is required. If I(create_mode=restore), this value is optional.
77 - Specifies the point in time (ISO8601 format) of the source database that will be restored to create the new database.
78 - Must be greater than or equal to the source database's earliestRestoreDate value.
79 type: str
80 recovery_services_recovery_point_resource_id:
81 description:
82 - Required if I(create_mode=restore_long_term_retention_backup), then this value is required.
83 - Specifies the resource ID of the recovery point to restore from.
84 type: str
85 edition:
86 description:
87 - (Deprecate)The edition of the database. The DatabaseEditions enumeration contains all the valid editions.
88 - This option will be deprecated in 2.11, use I(sku) instead.
89 - Cannot set C(sku) when this field set.
90 type: str
91 choices:
92 - 'web'
93 - 'business'
94 - 'basic'
95 - 'standard'
96 - 'premium'
97 - 'free'
98 - 'stretch'
99 - 'data_warehouse'
100 - 'system'
101 - 'system2'
102 sku:
103 description:
104 - The sku of the database. The DatabaseEditions enumeration contains all the valid sku.
105 - If I(create_mode=non_readable_secondary) or I(create_mode=online_secondary), this value is ignored.
106 - To see possible values, query the capabilities API (/subscriptions/{subscriptionId}/providers/Microsoft.Sql/locations/{locationID}/capabilities)
107 referred to by operationId:'Capabilities_ListByLocation'.
108 - Cannot set C(edition) when this field set.
109 type: dict
110 suboptions:
111 name:
112 description:
113 - Name of the database SKU, typically, a letter + Number code, e.g. P3
114 required: True
115 type: str
116 tier:
117 description:
118 - The tier or edition of the particular SKU, e.g. Basic, Premium
119 type: str
120 capacity:
121 description:
122 - Capacity of the particular SKU.
123 type: int
124 size:
125 description:
126 - Size of the particular SKU
127 type: str
128 family:
129 description:
130 - If the service has different generations of hardware, for the same SKU, then that can be used here
131 type: str
132 max_size_bytes:
133 description:
134 - The max size of the database expressed in bytes.
135 - If not I(create_mode=default), this value is ignored.
136 - To see possible values, query the capabilities API (/subscriptions/{subscriptionId}/providers/Microsoft.Sql/locations/{locationID}/capabilities).
137 referred to by operationId:'Capabilities_ListByLocation'.
138 type: str
139 elastic_pool_name:
140 description:
141 - The name of the elastic pool the database is in. Not supported for I(edition=data_warehouse).
142 type: str
143 read_scale:
144 description:
145 - If the database is a geo-secondary, indicates whether read-only connections are allowed to this database or not.
146 - Not supported for I(edition=data_warehouse).
147 type: bool
148 default: False
149 sample_name:
150 description:
151 - Indicates the name of the sample schema to apply when creating this database.
152 - If not I(create_mode=default), this value is ignored.
153 - Not supported for I(edition=data_warehouse).
154 type: str
155 choices:
156 - 'adventure_works_lt'
157 zone_redundant:
158 description:
159 - Is this database is zone redundant? It means the replicas of this database will be spread across multiple availability zones.
160 type: bool
161 default: False
162 force_update:
163 description:
164 - SQL Database will be updated if given parameters differ from existing resource state.
165 - To force SQL Database update in any circumstances set this parameter to True.
166 type: bool
167 state:
168 description:
169 - Assert the state of the SQL Database. Use C(present) to create or update an SQL Database and C(absent) to delete it.
170 default: present
171 type: str
172 choices:
173 - absent
174 - present
175
176 extends_documentation_fragment:
177 - azure.azcollection.azure
178 - azure.azcollection.azure_tags
179
180 author:
181 - Zim Kalinowski (@zikalino)
182
183 '''
184
185 EXAMPLES = '''
186 - name: Create (or update) SQL Database
187 azure_rm_sqldatabase:
188 resource_group: myResourceGroup
189 server_name: sqlcrudtest-5961
190 name: testdb
191 location: eastus
192
193 - name: Restore SQL Database
194 azure_rm_sqldatabase:
195 resource_group: myResourceGroup
196 server_name: sqlcrudtest-5961
197 name: restoreddb
198 location: eastus
199 create_mode: restore
200 source_database_deletion_date: '2024-07-26T17:50:01Z'
201
202 - name: Create SQL Database in Copy Mode
203 azure_rm_sqldatabase:
204 resource_group: myResourceGroup
205 server_name: sqlcrudtest-5961
206 name: copydb
207 location: eastus
208 create_mode: copy
209 source_database_id: "/subscriptions/xxxx-xxxx/resourceGroups/myResourceGroup/providers/Microsoft.Sql/servers/testsvr/databases/testdb"
210
211 - name: Create (or update) SQL Database with SKU
212 azure_rm_sqldatabase:
213 resource_group: myResourceGroup
214 server_name: sqlcrudtest-5961
215 name: testdb
216 location: eastus
217 sku:
218 name: S0
219 '''
220
221 RETURN = '''
222 id:
223 description:
224 - Resource ID.
225 returned: always
226 type: str
227 sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Sql/servers/sqlcrudtest-5961/databases/t
228 estdb"
229 database_id:
230 description:
231 - The ID of the database.
232 returned: always
233 type: str
234 sample: database_id
235 status:
236 description:
237 - The status of the database.
238 returned: always
239 type: str
240 sample: Online
241 '''
242
243 import time
244 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase, format_resource_id
245
246 try:
247 import dateutil.parser
248 from azure.core.exceptions import ResourceNotFoundError
249 from azure.core.polling import LROPoller
250 from azure.mgmt.sql.models import Sku
251 except ImportError:
252 # This is handled in azure_rm_common
253 pass
254
255 sku_spec = dict(
256 name=dict(type='str', required=True),
257 tier=dict(type='str'),
258 size=dict(type='str'),
259 family=dict(type='str'),
260 capacity=dict(type='int')
261 )
262
263
264 def get_sku_name(edition):
265 edition = edition.upper()
266 if edition == 'FREE':
267 return 'Free'
268 elif edition == 'SYSTEM':
269 return 'GP_Gen5_2'
270 elif edition in ['BUSINESS', 'SYSTEM2']:
271 return 'BC_Gen5_2'
272 elif edition == 'BASIC':
273 return 'Basic'
274 elif edition in ['STANDARD', 'WEB']:
275 return 'S1'
276 elif edition == 'PREMIUM':
277 return 'P2'
278 elif edition == 'STRETCH':
279 return 'DS100'
280 elif edition == 'DATA_WAREHOUSE':
281 return 'DW100c'
282 else:
283 return None
284
285
286 class Actions:
287 NoAction, Create, Update, Delete = range(4)
288
289
290 class AzureRMSqlDatabase(AzureRMModuleBase):
291 """Configuration class for an Azure RM SQL Database resource"""
292
293 def __init__(self):
294 self.module_arg_spec = dict(
295 resource_group=dict(
296 type='str',
297 required=True
298 ),
299 server_name=dict(
300 type='str',
301 required=True
302 ),
303 name=dict(
304 type='str',
305 required=True
306 ),
307 location=dict(
308 type='str'
309 ),
310 collation=dict(
311 type='str'
312 ),
313 create_mode=dict(
314 type='str',
315 choices=['copy',
316 'default',
317 'non_readable_secondary',
318 'online_secondary',
319 'point_in_time_restore',
320 'recovery',
321 'restore',
322 'restore_long_term_retention_backup']
323 ),
324 source_database_id=dict(
325 type='str'
326 ),
327 source_database_deletion_date=dict(
328 type='str'
329 ),
330 restore_point_in_time=dict(
331 type='str'
332 ),
333 recovery_services_recovery_point_resource_id=dict(
334 type='str'
335 ),
336 edition=dict(
337 type='str',
338 choices=['web',
339 'business',
340 'basic',
341 'standard',
342 'premium',
343 'free',
344 'stretch',
345 'data_warehouse',
346 'system',
347 'system2']
348 ),
349 sku=dict(
350 type='dict',
351 options=sku_spec
352 ),
353 max_size_bytes=dict(
354 type='str'
355 ),
356 elastic_pool_name=dict(
357 type='str'
358 ),
359 read_scale=dict(
360 type='bool',
361 default=False
362 ),
363 sample_name=dict(
364 type='str',
365 choices=['adventure_works_lt']
366 ),
367 zone_redundant=dict(
368 type='bool',
369 default=False
370 ),
371 force_update=dict(
372 type='bool'
373 ),
374 state=dict(
375 type='str',
376 default='present',
377 choices=['present', 'absent']
378 )
379 )
380
381 self.resource_group = None
382 self.server_name = None
383 self.name = None
384 self.parameters = dict()
385 self.tags = None
386
387 self.results = dict(changed=False)
388 self.state = None
389 self.to_do = Actions.NoAction
390
391 super(AzureRMSqlDatabase, self).__init__(derived_arg_spec=self.module_arg_spec,
392 supports_check_mode=True,
393 supports_tags=True)
394
395 def exec_module(self, **kwargs):
396 """Main module execution method"""
397
398 for key in list(self.module_arg_spec.keys()) + ['tags']:
399 if hasattr(self, key):
400 setattr(self, key, kwargs[key])
401 elif kwargs[key] is not None:
402 if key == "location":
403 self.parameters["location"] = kwargs[key]
404 elif key == "collation":
405 self.parameters["collation"] = kwargs[key]
406 elif key == "create_mode":
407 self.parameters["create_mode"] = _snake_to_camel(
408 kwargs[key], True)
409 elif key == "source_database_id":
410 self.parameters["source_database_id"] = kwargs[key]
411 elif key == "source_database_deletion_date":
412 try:
413 self.parameters["source_database_deletion_date"] = dateutil.parser.parse(kwargs[key])
414 except dateutil.parser._parser.ParserError:
415 self.fail("Error parsing date from source_database_deletion_date: {0}".format(kwargs[key]))
416 elif key == "restore_point_in_time":
417 try:
418 self.parameters["restore_point_in_time"] = dateutil.parser.parse(kwargs[key])
419 except dateutil.parser._parser.ParserError:
420 self.fail("Error parsing date from restore_point_in_time: {0}".format(kwargs[key]))
421 elif key == "recovery_services_recovery_point_resource_id":
422 self.parameters["recovery_services_recovery_point_resource_id"] = kwargs[key]
423 elif key == "edition":
424 ev = get_sku_name(kwargs[key])
425 self.parameters["sku"] = Sku(name=ev)
426 elif key == "sku":
427 ev = kwargs[key]
428 self.parameters["sku"] = Sku(
429 name=ev['name'], tier=ev['tier'], size=ev['size'], family=ev['family'], capacity=ev['capacity'])
430 elif key == "max_size_bytes":
431 self.parameters["max_size_bytes"] = kwargs[key]
432 elif key == "elastic_pool_name":
433 self.parameters["elastic_pool_id"] = kwargs[key]
434 elif key == "read_scale":
435 self.parameters["read_scale"] = 'Enabled' if kwargs[key] else 'Disabled'
436 elif key == "sample_name":
437 ev = kwargs[key]
438 if ev == 'adventure_works_lt':
439 ev = 'AdventureWorksLT'
440 self.parameters["sample_name"] = ev
441 elif key == "zone_redundant":
442 self.parameters["zone_redundant"] = True if kwargs[key] else False
443
444 old_response = None
445 response = None
446
447 resource_group = self.get_resource_group(self.resource_group)
448
449 if "location" not in self.parameters:
450 self.parameters["location"] = resource_group.location
451
452 if "elastic_pool_id" in self.parameters:
453 self.format_elastic_pool_id()
454
455 old_response = self.get_sqldatabase()
456
457 if not old_response:
458 self.log("SQL Database instance doesn't exist")
459 if self.state == 'absent':
460 self.log("Old instance didn't exist")
461 else:
462 self.to_do = Actions.Create
463 else:
464 self.log("SQL Database instance already exists")
465 if self.state == 'absent':
466 self.to_do = Actions.Delete
467 elif self.state == 'present':
468 self.log(
469 "Need to check if SQL Database instance has to be deleted or may be updated")
470 if ('location' in self.parameters) and (self.parameters['location'] != old_response['location']):
471 self.to_do = Actions.Update
472 if (('read_scale' in self.parameters) and
473 (self.parameters['read_scale'] != old_response['read_scale'])):
474 self.to_do = Actions.Update
475 if (('max_size_bytes' in self.parameters) and
476 (self.parameters['max_size_bytes'] != old_response['max_size_bytes'])):
477 self.to_do = Actions.Update
478 if (('sku' in self.parameters) and
479 (self.parameters['sku'].as_dict() != old_response['sku'])):
480 self.to_do = Actions.Update
481 update_tags, newtags = self.update_tags(
482 old_response.get('tags', dict()))
483 if update_tags:
484 self.tags = newtags
485 self.to_do = Actions.Update
486
487 if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
488 self.log("Need to Create / Update the SQL Database instance")
489
490 if self.check_mode:
491 self.results['changed'] = True
492 return self.results
493
494 self.parameters['tags'] = self.tags
495 response = self.create_update_sqldatabase()
496
497 if not old_response:
498 self.results['changed'] = True
499 else:
500 self.results['changed'] = old_response.__ne__(response)
501 self.log("Creation / Update done")
502 elif self.to_do == Actions.Delete:
503 self.log("SQL Database instance deleted")
504 self.results['changed'] = True
505
506 if self.check_mode:
507 return self.results
508
509 self.delete_sqldatabase()
510 # make sure instance is actually deleted, for some Azure resources, instance is hanging around
511 # for some time after deletion -- this should be really fixed in Azure
512 while self.get_sqldatabase():
513 time.sleep(20)
514 else:
515 self.log("SQL Database instance unchanged")
516 self.results['changed'] = False
517 response = old_response
518
519 if response:
520 self.results["id"] = response["id"]
521 self.results["database_id"] = response["database_id"]
522 self.results["status"] = response["status"]
523
524 return self.results
525
526 def create_update_sqldatabase(self):
527 '''
528 Creates or updates SQL Database with the specified configuration.
529
530 :return: deserialized SQL Database instance state dictionary
531 '''
532 self.log(
533 "Creating / Updating the SQL Database instance {0}".format(self.name))
534
535 try:
536 response = self.sql_client.databases.begin_create_or_update(resource_group_name=self.resource_group,
537 server_name=self.server_name,
538 database_name=self.name,
539 parameters=self.parameters)
540 if isinstance(response, LROPoller):
541 response = self.get_poller_result(response)
542 except Exception as exc:
543 self.log('Error attempting to create the SQL Database instance.')
544 self.fail(
545 "Error creating the SQL Database instance: {0}".format(str(exc)))
546 return response.as_dict()
547
548 def delete_sqldatabase(self):
549 '''
550 Deletes specified SQL Database instance in the specified subscription and resource group.
551
552 :return: True
553 '''
554 self.log("Deleting the SQL Database instance {0}".format(self.name))
555 try:
556 response = self.sql_client.databases.begin_delete(resource_group_name=self.resource_group,
557 server_name=self.server_name,
558 database_name=self.name)
559 if isinstance(response, LROPoller):
560 response = self.get_poller_result(response)
561 except Exception as e:
562 self.log('Error attempting to delete the SQL Database instance.')
563 self.fail(
564 "Error deleting the SQL Database instance: {0}".format(str(e)))
565
566 return True
567
568 def get_sqldatabase(self):
569 '''
570 Gets the properties of the specified SQL Database.
571
572 :return: deserialized SQL Database instance state dictionary
573 '''
574 self.log(
575 "Checking if the SQL Database instance {0} is present".format(self.name))
576 found = False
577 try:
578 response = self.sql_client.databases.get(resource_group_name=self.resource_group,
579 server_name=self.server_name,
580 database_name=self.name)
581 found = True
582 self.log("Response : {0}".format(response))
583 self.log("SQL Database instance : {0} found".format(response.name))
584 except ResourceNotFoundError:
585 self.log('Did not find the SQL Database instance.')
586 if found is True:
587 return response.as_dict()
588
589 return False
590
591 def format_elastic_pool_id(self):
592 parrent_id = format_resource_id(val=self.server_name,
593 subscription_id=self.subscription_id,
594 namespace="Microsoft.Sql",
595 types="servers",
596 resource_group=self.resource_group)
597 self.parameters['elastic_pool_id'] = parrent_id + \
598 "/elasticPools/" + self.parameters['elastic_pool_id']
599
600
601 def _snake_to_camel(snake, capitalize_first=False):
602 if capitalize_first:
603 return ''.join(x.capitalize() or '_' for x in snake.split('_'))
604 else:
605 return snake.split('_')[0] + ''.join(x.capitalize() or '_' for x in snake.split('_')[1:])
606
607
608 def main():
609 """Main execution"""
610 AzureRMSqlDatabase()
611
612
613 if __name__ == '__main__':
614 main()