Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2017 Zim Kalinowski, <[email protected]>
4 # Copyright (c) 2019 Matti Ranta, (@techknowlogick)
5 #
6 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11
12 DOCUMENTATION = '''
13 ---
14 module: azure_rm_mariadbserver
15 version_added: "0.1.2"
16 short_description: Manage MariaDB Server instance
17 description:
18 - Create, update and delete instance of MariaDB Server.
19
20 options:
21 resource_group:
22 description:
23 - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
24 required: True
25 type: str
26 name:
27 description:
28 - The name of the server.
29 required: True
30 type: str
31 sku:
32 description:
33 - The SKU (pricing tier) of the server.
34 type: dict
35 suboptions:
36 name:
37 description:
38 - The name of the SKU, typically, tier + family + cores, for example C(B_Gen4_1), C(GP_Gen5_8).
39 type: str
40 tier:
41 description:
42 - The tier of the particular SKU, for example C(Basic).
43 type: str
44 choices:
45 - basic
46 - standard
47 capacity:
48 description:
49 - The scale up/out capacity, representing server's compute units.
50 type: int
51 size:
52 description:
53 - The size code, to be interpreted by resource as appropriate.
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_mb:
59 description:
60 - The maximum storage allowed for a server.
61 type: int
62 version:
63 description:
64 - Server version.
65 type: str
66 choices:
67 - '10.2'
68 - '10.3'
69 enforce_ssl:
70 description:
71 - Enable SSL enforcement.
72 type: bool
73 default: False
74 admin_username:
75 description:
76 - The administrator's login name of a server. Can only be specified when the server is being created (and is required for creation).
77 type: str
78 admin_password:
79 description:
80 - The password of the administrator login.
81 type: str
82 create_mode:
83 description:
84 - Create mode of SQL Server.
85 type: str
86 default: Default
87 state:
88 description:
89 - Assert the state of the MariaDB Server. Use C(present) to create or update a server and C(absent) to delete it.
90 default: present
91 type: str
92 choices:
93 - absent
94 - present
95
96 extends_documentation_fragment:
97 - azure.azcollection.azure
98 - azure.azcollection.azure_tags
99
100 author:
101 - Zim Kalinowski (@zikalino)
102 - Matti Ranta (@techknowlogick)
103
104 '''
105
106 EXAMPLES = '''
107 - name: Create (or update) MariaDB Server
108 azure_rm_mariadbserver:
109 resource_group: myResourceGroup
110 name: testserver
111 sku:
112 name: B_Gen5_1
113 tier: Basic
114 location: eastus
115 storage_mb: 1024
116 enforce_ssl: true
117 version: 10.2
118 admin_username: cloudsa
119 admin_password: "{{ password }}"
120 '''
121
122 RETURN = '''
123 id:
124 description:
125 - Resource ID.
126 returned: always
127 type: str
128 sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DBforMariaDB/servers/mariadbsrv1b6dd89593
129 version:
130 description:
131 - Server version. Possible values include C(10.2) and C(10.3).
132 returned: always
133 type: str
134 sample: 10.2
135 state:
136 description:
137 - A state of a server that is visible to user. Possible values include C(Ready), C(Dropping), C(Disabled).
138 returned: always
139 type: str
140 sample: Ready
141 fully_qualified_domain_name:
142 description:
143 - The fully qualified domain name of a server.
144 returned: always
145 type: str
146 sample: mariadbsrv1b6dd89593.mariadb.database.azure.com
147 '''
148
149 import time
150
151 try:
152 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
153 from azure.core.exceptions import ResourceNotFoundError
154 from azure.core.polling import LROPoller
155 except ImportError:
156 # This is handled in azure_rm_common
157 pass
158
159
160 class Actions:
161 NoAction, Create, Update, Delete = range(4)
162
163
164 class AzureRMMariaDbServers(AzureRMModuleBase):
165 """Configuration class for an Azure RM MariaDB Server resource"""
166
167 def __init__(self):
168 self.module_arg_spec = dict(
169 resource_group=dict(
170 type='str',
171 required=True
172 ),
173 name=dict(
174 type='str',
175 required=True
176 ),
177 sku=dict(
178 type='dict'
179 ),
180 location=dict(
181 type='str'
182 ),
183 storage_mb=dict(
184 type='int'
185 ),
186 version=dict(
187 type='str',
188 choices=['10.2', '10.3']
189 ),
190 enforce_ssl=dict(
191 type='bool',
192 default=False
193 ),
194 create_mode=dict(
195 type='str',
196 default='Default'
197 ),
198 admin_username=dict(
199 type='str'
200 ),
201 admin_password=dict(
202 type='str',
203 no_log=True
204 ),
205 state=dict(
206 type='str',
207 default='present',
208 choices=['present', 'absent']
209 )
210 )
211
212 self.resource_group = None
213 self.name = None
214 self.parameters = dict()
215 self.tags = None
216
217 self.results = dict(changed=False)
218 self.state = None
219 self.to_do = Actions.NoAction
220
221 super(AzureRMMariaDbServers, self).__init__(derived_arg_spec=self.module_arg_spec,
222 supports_check_mode=True,
223 supports_tags=True)
224
225 def exec_module(self, **kwargs):
226 """Main module execution method"""
227
228 for key in list(self.module_arg_spec.keys()) + ['tags']:
229 if hasattr(self, key):
230 setattr(self, key, kwargs[key])
231 elif kwargs[key] is not None:
232 if key == "sku":
233 ev = kwargs[key]
234 if 'tier' in ev:
235 if ev['tier'] == 'basic':
236 ev['tier'] = 'Basic'
237 elif ev['tier'] == 'standard':
238 ev['tier'] = 'Standard'
239 self.parameters["sku"] = ev
240 elif key == "location":
241 self.parameters["location"] = kwargs[key]
242 elif key == "storage_mb":
243 self.parameters.setdefault("properties", {}).setdefault("storage_profile", {})["storage_mb"] = kwargs[key]
244 elif key == "version":
245 self.parameters.setdefault("properties", {})["version"] = kwargs[key]
246 elif key == "enforce_ssl":
247 self.parameters.setdefault("properties", {})["ssl_enforcement"] = 'Enabled' if kwargs[key] else 'Disabled'
248 elif key == "create_mode":
249 self.parameters.setdefault("properties", {})["create_mode"] = kwargs[key]
250 elif key == "admin_username":
251 self.parameters.setdefault("properties", {})["administrator_login"] = kwargs[key]
252 elif key == "admin_password":
253 self.parameters.setdefault("properties", {})["administrator_login_password"] = kwargs[key]
254
255 old_response = None
256 response = None
257
258 resource_group = self.get_resource_group(self.resource_group)
259
260 if "location" not in self.parameters:
261 self.parameters["location"] = resource_group.location
262
263 old_response = self.get_mariadbserver()
264
265 if not old_response:
266 self.log("MariaDB Server instance doesn't exist")
267 if self.state == 'absent':
268 self.log("Old instance didn't exist")
269 else:
270 self.to_do = Actions.Create
271 else:
272 self.log("MariaDB Server instance already exists")
273 if self.state == 'absent':
274 self.to_do = Actions.Delete
275 elif self.state == 'present':
276 self.log("Need to check if MariaDB Server instance has to be deleted or may be updated")
277 update_tags, newtags = self.update_tags(old_response.get('tags', {}))
278 if update_tags:
279 self.tags = newtags
280 self.to_do = Actions.Update
281
282 if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
283 self.log("Need to Create / Update the MariaDB Server instance")
284
285 if self.check_mode:
286 self.results['changed'] = True
287 return self.results
288
289 response = self.create_update_mariadbserver()
290
291 if not old_response:
292 self.results['changed'] = True
293 else:
294 self.results['changed'] = old_response.__ne__(response)
295 self.log("Creation / Update done")
296 elif self.to_do == Actions.Delete:
297 self.log("MariaDB Server instance deleted")
298 self.results['changed'] = True
299
300 if self.check_mode:
301 return self.results
302
303 self.delete_mariadbserver()
304 # make sure instance is actually deleted, for some Azure resources, instance is hanging around
305 # for some time after deletion -- this should be really fixed in Azure
306 while self.get_mariadbserver():
307 time.sleep(20)
308 else:
309 self.log("MariaDB Server instance unchanged")
310 self.results['changed'] = False
311 response = old_response
312
313 if response:
314 self.results["id"] = response["id"]
315 self.results["version"] = response["version"]
316 self.results["state"] = response["user_visible_state"]
317 self.results["fully_qualified_domain_name"] = response["fully_qualified_domain_name"]
318
319 return self.results
320
321 def create_update_mariadbserver(self):
322 '''
323 Creates or updates MariaDB Server with the specified configuration.
324
325 :return: deserialized MariaDB Server instance state dictionary
326 '''
327 self.log("Creating / Updating the MariaDB Server instance {0}".format(self.name))
328
329 try:
330 self.parameters['tags'] = self.tags
331 if self.to_do == Actions.Create:
332 response = self.mariadb_client.servers.begin_create(resource_group_name=self.resource_group,
333 server_name=self.name,
334 parameters=self.parameters)
335 else:
336 # structure of parameters for update must be changed
337 self.parameters.update(self.parameters.pop("properties", {}))
338 response = self.mariadb_client.servers.begin_update(resource_group_name=self.resource_group,
339 server_name=self.name,
340 parameters=self.parameters)
341 if isinstance(response, LROPoller):
342 response = self.get_poller_result(response)
343
344 except Exception as exc:
345 self.log('Error attempting to create the MariaDB Server instance.')
346 self.fail("Error creating the MariaDB Server instance: {0}".format(str(exc)))
347 return response.as_dict()
348
349 def delete_mariadbserver(self):
350 '''
351 Deletes specified MariaDB Server instance in the specified subscription and resource group.
352
353 :return: True
354 '''
355 self.log("Deleting the MariaDB Server instance {0}".format(self.name))
356 try:
357 response = self.mariadb_client.servers.begin_delete(resource_group_name=self.resource_group,
358 server_name=self.name)
359 except Exception as e:
360 self.log('Error attempting to delete the MariaDB Server instance.')
361 self.fail("Error deleting the MariaDB Server instance: {0}".format(str(e)))
362
363 return True
364
365 def get_mariadbserver(self):
366 '''
367 Gets the properties of the specified MariaDB Server.
368
369 :return: deserialized MariaDB Server instance state dictionary
370 '''
371 self.log("Checking if the MariaDB Server instance {0} is present".format(self.name))
372 found = False
373 try:
374 response = self.mariadb_client.servers.get(resource_group_name=self.resource_group,
375 server_name=self.name)
376 found = True
377 self.log("Response : {0}".format(response))
378 self.log("MariaDB Server instance : {0} found".format(response.name))
379 except ResourceNotFoundError as e:
380 self.log('Did not find the MariaDB Server instance.')
381 if found is True:
382 return response.as_dict()
383
384 return False
385
386
387 def main():
388 """Main execution"""
389 AzureRMMariaDbServers()
390
391
392 if __name__ == '__main__':
393 main()