Debian Codegraph @

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