Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_mysqlserver.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_mysqlserver
14 version_added: "0.1.2"
15 short_description: Manage MySQL Server instance
16 description:
17 - Create, update and delete instance of MySQL 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 sku:
31 description:
32 - The SKU (pricing tier) of the server.
33 type: dict
34 suboptions:
35 name:
36 description:
37 - The name of the sku, typically, tier + family + cores, for example C(B_Gen4_1), C(GP_Gen5_8).
38 type: str
39 tier:
40 description:
41 - The tier of the particular SKU, for example C(Basic).
42 type: str
43 choices:
44 - basic
45 - standard
46 capacity:
47 description:
48 - The scale up/out capacity, representing server's compute units.
49 type: str
50 size:
51 description:
52 - The size code, to be interpreted by resource as appropriate.
53 type: int
54 location:
55 description:
56 - Resource location. If not set, location from the resource group will be used as default.
57 type: str
58 storage_profile:
59 description:
60 - Storage Profile properties of a server.
61 type: dict
62 suboptions:
63 storage_mb:
64 description:
65 - The maximum storage allowed for a server.
66 type: int
67 backup_retention_days:
68 description:
69 - Backup retention days for the server
70 type: int
71 geo_redundant_backup:
72 description:
73 - Enable Geo-redundant or not for server backup.
74 type: str
75 choices:
76 - Disabled
77 - Enabled
78 storage_autogrow:
79 description:
80 - Enable Storage Auto Grow.
81 type: str
82 choices:
83 - Disabled
84 - Enabled
85 version:
86 description:
87 - Server version.
88 type: str
89 choices:
90 - '5.7'
91 - '8.0'
92 enforce_ssl:
93 description:
94 - Enable SSL enforcement.
95 type: bool
96 default: False
97 admin_username:
98 description:
99 - The administrator's login name of a server.
100 - Can only be specified when the server is being created (and is required for creation).
101 type: str
102 admin_password:
103 description:
104 - The password of the administrator login.
105 type: str
106 create_mode:
107 description:
108 - Create mode of SQL Server.
109 default: Default
110 type: str
111 restarted:
112 description:
113 - Set to C(true) with I(state=present) to restart a running mysql server.
114 default: False
115 type: bool
116 state:
117 description:
118 - Assert the state of the MySQL Server. Use C(present) to create or update a server and C(absent) to delete it.
119 default: present
120 type: str
121 choices:
122 - absent
123 - present
124
125 extends_documentation_fragment:
126 - azure.azcollection.azure
127 - azure.azcollection.azure_tags
128
129 author:
130 - Zim Kalinowski (@zikalino)
131
132 '''
133
134 EXAMPLES = '''
135 - name: Create (or update) MySQL Server
136 azure_rm_mysqlserver:
137 resource_group: myResourceGroup
138 name: testserver
139 sku:
140 name: B_Gen5_1
141 tier: Basic
142 location: eastus
143 storage_profile:
144 storage_mb: 51200
145 backup_retention_days: 7
146 geo_redundant_backup: Disabled
147 storage_autogrow: Disabled
148 enforce_ssl: true
149 version: 5.7
150 admin_username: cloudsa
151 admin_password: "{{ password }}"
152 '''
153
154 RETURN = '''
155 id:
156 description:
157 - Resource ID.
158 returned: always
159 type: str
160 sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DBforMySQL/servers/mysqlsrv1b6dd89593
161 version:
162 description:
163 - Server version. Possible values include C(5.6), C(5.7), C(8.0).
164 returned: always
165 type: str
166 sample: 5.7
167 state:
168 description:
169 - A state of a server that is visible to user. Possible values include C(Ready), C(Dropping), C(Disabled).
170 returned: always
171 type: str
172 sample: Ready
173 fully_qualified_domain_name:
174 description:
175 - The fully qualified domain name of a server.
176 returned: always
177 type: str
178 sample: mysqlsrv1b6dd89593.mysql.database.azure.com
179 '''
180
181 import time
182
183 try:
184 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
185 from azure.core.exceptions import ResourceNotFoundError
186 from azure.core.polling import LROPoller
187 except ImportError:
188 # This is handled in azure_rm_common
189 pass
190
191 storage_profile_spec = dict(
192 storage_mb=dict(
193 type='int'
194 ),
195 backup_retention_days=dict(
196 type='int'
197 ),
198 geo_redundant_backup=dict(
199 type='str',
200 choices=['Disabled', 'Enabled']
201 ),
202 storage_autogrow=dict(
203 type='str',
204 choices=['Disabled', 'Enabled']
205 )
206 )
207
208
209 class Actions:
210 NoAction, Create, Update, Delete = range(4)
211
212
213 class AzureRMMySqlServers(AzureRMModuleBase):
214 """Configuration class for an Azure RM MySQL Server resource"""
215
216 def __init__(self):
217 self.module_arg_spec = dict(
218 resource_group=dict(
219 type='str',
220 required=True
221 ),
222 name=dict(
223 type='str',
224 required=True
225 ),
226 sku=dict(
227 type='dict'
228 ),
229 location=dict(
230 type='str'
231 ),
232 storage_profile=dict(
233 type='dict',
234 options=storage_profile_spec
235 ),
236 version=dict(
237 type='str',
238 choices=['5.7', '8.0']
239 ),
240 enforce_ssl=dict(
241 type='bool',
242 default=False
243 ),
244 create_mode=dict(
245 type='str',
246 default='Default'
247 ),
248 admin_username=dict(
249 type='str'
250 ),
251 restarted=dict(
252 type='bool',
253 default=False
254 ),
255 admin_password=dict(
256 type='str',
257 no_log=True
258 ),
259 state=dict(
260 type='str',
261 default='present',
262 choices=['present', 'absent']
263 )
264 )
265
266 self.resource_group = None
267 self.name = None
268 self.parameters = dict()
269 self.tags = None
270 self.restarted = False
271
272 self.results = dict(changed=False)
273 self.state = None
274 self.to_do = Actions.NoAction
275
276 super(AzureRMMySqlServers, self).__init__(derived_arg_spec=self.module_arg_spec,
277 supports_check_mode=True,
278 supports_tags=True)
279
280 def exec_module(self, **kwargs):
281 """Main module execution method"""
282
283 for key in list(self.module_arg_spec.keys()) + ['tags']:
284 if hasattr(self, key):
285 setattr(self, key, kwargs[key])
286 elif kwargs[key] is not None:
287 if key == "sku":
288 ev = kwargs[key]
289 if 'tier' in ev:
290 if ev['tier'] == 'basic':
291 ev['tier'] = 'Basic'
292 elif ev['tier'] == 'standard':
293 ev['tier'] = 'Standard'
294 self.parameters["sku"] = ev
295 elif key == "location":
296 self.parameters["location"] = kwargs[key]
297 elif key == "storage_profile":
298 self.parameters.setdefault("properties", {})["storage_profile"] = kwargs[key]
299 elif key == "version":
300 self.parameters.setdefault("properties", {})["version"] = kwargs[key]
301 elif key == "enforce_ssl":
302 self.parameters.setdefault("properties", {})["ssl_enforcement"] = 'Enabled' if kwargs[key] else 'Disabled'
303 elif key == "create_mode":
304 self.parameters.setdefault("properties", {})["create_mode"] = kwargs[key]
305 elif key == "admin_username":
306 self.parameters.setdefault("properties", {})["administrator_login"] = kwargs[key]
307 elif key == "admin_password":
308 self.parameters.setdefault("properties", {})["administrator_login_password"] = kwargs[key]
309
310 old_response = None
311 response = None
312
313 resource_group = self.get_resource_group(self.resource_group)
314
315 if "location" not in self.parameters:
316 self.parameters["location"] = resource_group.location
317
318 old_response = self.get_mysqlserver()
319
320 if not old_response:
321 self.log("MySQL Server instance doesn't exist")
322 if self.restarted:
323 self.fail("Mysql server instance doesn't exist, can't be restart")
324
325 if self.state == 'absent':
326 self.log("Old instance didn't exist")
327 else:
328 self.to_do = Actions.Create
329 else:
330 if self.restarted:
331 self.restart_mysqlserver()
332 self.results['changed'] = True
333 self.results['state'] = old_response
334 return self.results
335
336 self.log("MySQL Server instance already exists")
337 if self.state == 'absent':
338 self.to_do = Actions.Delete
339 elif self.state == 'present':
340 self.log("Need to check if MySQL Server instance has to be deleted or may be updated")
341 update_tags, newtags = self.update_tags(old_response.get('tags', {}))
342 if update_tags:
343 self.tags = newtags
344 self.to_do = Actions.Update
345
346 if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
347 self.log("Need to Create / Update the MySQL Server instance")
348
349 if self.check_mode:
350 self.results['changed'] = True
351 return self.results
352
353 response = self.create_update_mysqlserver()
354
355 if not old_response:
356 self.results['changed'] = True
357 else:
358 self.results['changed'] = old_response.__ne__(response)
359 self.log("Creation / Update done")
360 elif self.to_do == Actions.Delete:
361 self.log("MySQL Server instance deleted")
362 self.results['changed'] = True
363
364 if self.check_mode:
365 return self.results
366
367 self.delete_mysqlserver()
368 # make sure instance is actually deleted, for some Azure resources, instance is hanging around
369 # for some time after deletion -- this should be really fixed in Azure
370 while self.get_mysqlserver():
371 time.sleep(20)
372 else:
373 self.log("MySQL Server instance unchanged")
374 self.results['changed'] = False
375 response = old_response
376
377 if response:
378 self.results["id"] = response["id"]
379 self.results["version"] = response["version"]
380 self.results["state"] = response["user_visible_state"]
381 self.results["fully_qualified_domain_name"] = response["fully_qualified_domain_name"]
382
383 return self.results
384
385 def restart_mysqlserver(self):
386 '''
387 Restart MySQL Server.
388 '''
389 self.log("Restart MySQL Server instance {0}".format(self.name))
390
391 try:
392 response = self.mysql_client.servers.begin_restart(resource_group_name=self.resource_group, server_name=self.name)
393 except Exception as exc:
394 self.fail("Error restarting mysql server {0} - {1}".format(self.name, str(exc)))
395 return True
396
397 def create_update_mysqlserver(self):
398 '''
399 Creates or updates MySQL Server with the specified configuration.
400
401 :return: deserialized MySQL Server instance state dictionary
402 '''
403 self.log("Creating / Updating the MySQL Server instance {0}".format(self.name))
404
405 try:
406 self.parameters['tags'] = self.tags
407 if self.to_do == Actions.Create:
408 response = self.mysql_client.servers.begin_create(resource_group_name=self.resource_group,
409 server_name=self.name,
410 parameters=self.parameters)
411 else:
412 # structure of parameters for update must be changed
413 self.parameters.update(self.parameters.pop("properties", {}))
414 response = self.mysql_client.servers.begin_update(resource_group_name=self.resource_group,
415 server_name=self.name,
416 parameters=self.parameters)
417 if isinstance(response, LROPoller):
418 response = self.get_poller_result(response)
419
420 except Exception as exc:
421 self.log('Error attempting to create the MySQL Server instance.')
422 self.fail("Error creating the MySQL Server instance: {0}".format(str(exc)))
423 return response.as_dict()
424
425 def delete_mysqlserver(self):
426 '''
427 Deletes specified MySQL Server instance in the specified subscription and resource group.
428
429 :return: True
430 '''
431 self.log("Deleting the MySQL Server instance {0}".format(self.name))
432 try:
433 response = self.mysql_client.servers.begin_delete(resource_group_name=self.resource_group,
434 server_name=self.name)
435 except Exception as e:
436 self.log('Error attempting to delete the MySQL Server instance.')
437 self.fail("Error deleting the MySQL Server instance: {0}".format(str(e)))
438
439 return True
440
441 def get_mysqlserver(self):
442 '''
443 Gets the properties of the specified MySQL Server.
444
445 :return: deserialized MySQL Server instance state dictionary
446 '''
447 self.log("Checking if the MySQL Server instance {0} is present".format(self.name))
448 found = False
449 try:
450 response = self.mysql_client.servers.get(resource_group_name=self.resource_group,
451 server_name=self.name)
452 found = True
453 self.log("Response : {0}".format(response))
454 self.log("MySQL Server instance : {0} found".format(response.name))
455 except ResourceNotFoundError as e:
456 self.log('Did not find the MySQL Server instance.')
457 if found is True:
458 return response.as_dict()
459
460 return False
461
462
463 def main():
464 """Main execution"""
465 AzureRMMySqlServers()
466
467
468 if __name__ == '__main__':
469 main()