Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_sqlserver.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_sqlserver
14 version_added: "0.1.2"
15 short_description: Manage SQL Server instance
16 description:
17 - Create, update and delete instance of SQL 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 type: str
24 required: True
25 name:
26 description:
27 - The name of the server.
28 type: str
29 required: True
30 location:
31 description:
32 - Resource location.
33 type: str
34 admin_username:
35 description:
36 - Username of the SQL administrator account for server. Once created it cannot be changed.
37 type: str
38 admin_password:
39 description:
40 - Password of the SQL administrator account for server (required for server creation).
41 type: str
42 version:
43 description:
44 - The version of the server. For example C(12.0).
45 type: str
46 identity:
47 description:
48 - Specifies the managed identity to be used with SqlServer.
49 - If a string, the Managed identity type is based on the name.
50 - Possible values include C(SystemAssigned) and C(None).
51 - If a dict with the keys I(type), I(user_assigned_identities)
52 - Possible values for I(type) include C(SystemAssigned, C(UserAssigned),
53 C(SystemAssigned, UserAssigned), and C(None).
54 - Possible values for I(user_assigned_identities) include a dict
55 with I(id) and I(append).
56 - Possible values for I(id) is a list of user assigned identities ID's
57 - Possible values for I(append) is a boolean of True to append identities
58 or False to overwrite with new I(id)'s.
59 - The string format is (deprecated) and the new dict format should be used
60 going forward.
61 type: raw
62 primary_user_assigned_identity_id:
63 description:
64 - Specifies the primary User Assigned Identity to use.
65 - This is required if you are using Managed Identity type of UserAssigned
66 type: str
67 version_added: "2.7.0"
68 minimal_tls_version:
69 description:
70 - Require clients to use a specified TLS version.
71 type: str
72 choices:
73 - '1.0'
74 - '1.1'
75 - '1.2'
76 version_added: "1.11.0"
77 public_network_access:
78 description:
79 - Whether or not public endpoint access is allowed for the server.
80 type: str
81 choices:
82 - Enabled
83 - Disabled
84 version_added: "1.11.0"
85 restrict_outbound_network_access:
86 description:
87 - Whether or not to restrict outbound network access for this server.
88 type: str
89 choices:
90 - Enabled
91 - Disabled
92 version_added: "1.11.0"
93 change_admin_password:
94 description:
95 - Whether or not the I(admin_password) should be updated for an existing server. If C(true), the password is the only value which will be updated.
96 type: bool
97 default: false
98 version_added: "1.11.0"
99 administrators:
100 description:
101 - The Azure Active Directory identity of the server.
102 type: dict
103 suboptions:
104 administrator_type:
105 description:
106 - Type of the Azure AD administrator.
107 type: str
108 default: ActiveDirectory
109 principal_type:
110 description:
111 - Principal Type of the Azure AD administrator.
112 type: str
113 choices:
114 - User
115 - Group
116 - Application
117 login:
118 description:
119 - Login name of the Azure AD administrator.
120 type: str
121 sid:
122 description:
123 - SID (object ID) of the Azure AD administrator.
124 type: str
125 tenant_id:
126 description:
127 - Tenant ID of the Azure AD administrator.
128 type: str
129 azure_ad_only_authentication:
130 description:
131 - Azure AD only authentication enabled.
132 type: bool
133 version_added: "1.11.0"
134 state:
135 description:
136 - State of the SQL server. Use C(present) to create or update a server and use C(absent) to delete a server.
137 default: present
138 type: str
139 choices:
140 - absent
141 - present
142
143 extends_documentation_fragment:
144 - azure.azcollection.azure
145 - azure.azcollection.azure_tags
146
147 author:
148 - Zim Kalinowski (@zikalino)
149
150 '''
151
152 EXAMPLES = '''
153 - name: Create (or update) SQL Server
154 azure_rm_sqlserver:
155 resource_group: myResourceGroup
156 name: server_name
157 location: westus
158 admin_username: mylogin
159 admin_password: "{{ password }}"
160
161 - name: Change SQL Server admin password
162 azure_rm_sqlserver:
163 resource_group: myResourceGroup
164 name: server_name
165 location: westus
166 admin_password: "{{ password }}"
167 change_admin_password: true
168
169 - name: Create SQL Server with Azure Active Directory admin
170 azure_rm_sqlserver:
171 resource_group: myResourceGroup
172 name: server_name
173 location: westus
174 admin_username: mylogin
175 admin_password: "{{ password }}"
176 administrators:
177 principal_type: Group
178 login: MySqlAdminGroup
179 sid: "{{ MySqlAdminGroup.object_id }}"
180 tenant_id: "{{ my_tenant_id }}"
181 azure_ad_only_authentication: false
182 '''
183
184 RETURN = '''
185 id:
186 description:
187 - Resource ID.
188 returned: always
189 type: str
190 sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Sql/servers/sqlcrudtest-4645
191 version:
192 description:
193 - The version of the server.
194 returned: always
195 type: str
196 sample: 12.0
197 state:
198 description:
199 - The state of the server.
200 returned: always
201 type: str
202 sample: state
203 fully_qualified_domain_name:
204 description:
205 - The fully qualified domain name of the server.
206 returned: always
207 type: str
208 sample: sqlcrudtest-4645.database.windows.net
209 '''
210
211 import time
212 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
213
214 try:
215 from azure.core.exceptions import ResourceNotFoundError
216 from azure.core.polling import LROPoller
217 from azure.mgmt.sql.models import (ResourceIdentity, UserIdentity)
218 except ImportError:
219 # This is handled in azure_rm_common
220 pass
221
222
223 class Actions:
224 NoAction, Create, Update, Delete = range(4)
225
226
227 administrators_spec = dict(
228 administrator_type=dict(type='str', default='ActiveDirectory'),
229 principal_type=dict(type='str', choices=['User', 'Group', 'Application']),
230 login=dict(type='str'),
231 sid=dict(type='str'),
232 tenant_id=dict(type='str'),
233 azure_ad_only_authentication=dict(type='bool'),
234 )
235
236
237 class AzureRMSqlServer(AzureRMModuleBaseExt):
238 """Configuration class for an Azure RM SQL Server resource"""
239
240 def __init__(self):
241 self.module_arg_spec = dict(
242 resource_group=dict(
243 type='str',
244 required=True
245 ),
246 name=dict(
247 type='str',
248 required=True
249 ),
250 location=dict(
251 type='str'
252 ),
253 admin_username=dict(
254 type='str'
255 ),
256 admin_password=dict(
257 type='str',
258 no_log=True
259 ),
260 version=dict(
261 type='str'
262 ),
263 identity=dict(
264 type='raw'
265 ),
266 primary_user_assigned_identity_id=dict(
267 type='str',
268 ),
269 minimal_tls_version=dict(
270 type="str",
271 choices=["1.0", "1.1", "1.2"]
272 ),
273 public_network_access=dict(
274 type="str",
275 choices=["Enabled", "Disabled"]
276 ),
277 restrict_outbound_network_access=dict(
278 type="str",
279 choices=["Enabled", "Disabled"]
280 ),
281 change_admin_password=dict(
282 type="bool",
283 default=False,
284 no_log=False,
285 ),
286 administrators=dict(
287 type='dict',
288 options=administrators_spec,
289 ),
290 state=dict(
291 type='str',
292 default='present',
293 choices=['present', 'absent']
294 )
295 )
296
297 self.resource_group = None
298 self.name = None
299 self.parameters = dict()
300 self.tags = None
301 # Managed Identity
302 self.identity = None
303
304 self.results = dict(changed=False)
305 self.state = None
306 self.to_do = Actions.NoAction
307 self.change_admin_password = False
308 self._managed_identity = None
309
310 super(AzureRMSqlServer, self).__init__(derived_arg_spec=self.module_arg_spec,
311 supports_check_mode=True,
312 supports_tags=True)
313
314 @property
315 def managed_identity(self):
316 if not self._managed_identity:
317 self._managed_identity = {"identity": ResourceIdentity,
318 "user_assigned": UserIdentity
319 }
320 return self._managed_identity
321
322 def validate_identity_parameter(self):
323 errors = []
324 valid_identity_keys = ['type', 'user_assigned_identities']
325 valid_user_assigned_keys = ['id', 'append']
326 type_choices = ['SystemAssigned',
327 'UserAssigned',
328 'SystemAssigned, UserAssigned',
329 'None']
330 for key in self.identity.keys():
331 if key not in valid_identity_keys:
332 errors.append("Invalid key {0}".format(key))
333 # Default option for type is "None"
334 self.identity["type"] = self.identity.get("type", "None")
335 if self.identity.get("type") not in type_choices:
336 errors.append("Invalid identity->type, Valid choices are: [{0}]".format(type_choices))
337 for key in self.identity.get("user_assigned_identities", dict()).keys():
338 if key not in valid_user_assigned_keys:
339 errors.append("Invalid key {0}".format(key))
340 if key == "append":
341 if isinstance(self.identity['user_assigned_identities'][key], bool) is not True:
342 errors.append("identity->user_assigned_identity->append must be True or False")
343
344 if errors:
345 self.fail(msg="Some required options are missing from managed identity configuration.", errors=errors)
346
347 def exec_module(self, **kwargs):
348 """Main module execution method"""
349
350 for key in list(self.module_arg_spec.keys()) + ['tags']:
351 if hasattr(self, key):
352 setattr(self, key, kwargs[key])
353 elif kwargs[key] is not None:
354 if key == "admin_username":
355 self.parameters.update({"administrator_login": kwargs[key]})
356 elif key == "admin_password":
357 self.parameters.update({"administrator_login_password": kwargs[key]})
358 elif key == "primary_user_assigned_identity_id":
359 self.parameters.update({"primary_user_assigned_identity_id": kwargs[key]})
360 else:
361 self.parameters[key] = kwargs[key]
362
363 old_response = None
364 response = None
365
366 resource_group = self.get_resource_group(self.resource_group)
367
368 if "location" not in self.parameters:
369 self.parameters["location"] = resource_group.location
370
371 old_response = self.get_sqlserver()
372
373 if self.identity and isinstance(self.identity, dict):
374 self.validate_identity_parameter()
375 update_identity, identity = self.update_managed_identity(new_identity=self.identity,
376 curr_identity=old_response.get('identity') if old_response else None)
377 if update_identity:
378 self.parameters.update({"identity": identity.as_dict()})
379 elif self.identity and isinstance(self.identity, str):
380 self.parameters.update({"identity": {"type": self.identity}})
381 self.module.warn('Specifying the identity type as a string is deprecated, please update your playbook.')
382 elif self.identity:
383 self.fail("parameter error: expecting identity to be a string or dict not {0}".format(type(self.identity).__name__))
384
385 if not old_response:
386 self.log("SQL Server instance doesn't exist")
387 if self.state == 'absent':
388 self.log("Old instance didn't exist")
389 else:
390 self.to_do = Actions.Create
391 else:
392 self.log("SQL Server instance already exists")
393 if self.state == 'absent':
394 self.to_do = Actions.Delete
395 elif self.state == 'present':
396 self.log("Need to check if SQL Server instance has to be deleted or may be updated")
397 update_tags, newtags = self.update_tags(old_response.get('tags', dict()))
398 if update_tags:
399 self.tags = newtags
400 admin_pass = self.parameters.pop('administrator_login_password', None) # remove for comparison as value not returned in old_response
401 if self.change_admin_password:
402 self.parameters.update(old_response) # use all existing config
403 self.parameters.update({"administrator_login_password": admin_pass})
404 self.results['compare'] = []
405 if not self.idempotency_check(old_response, self.parameters):
406 self.to_do = Actions.Update
407
408 if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
409 self.log("Need to Create / Update the SQL Server instance")
410
411 if self.check_mode:
412 self.results['changed'] = True
413 return self.results
414
415 self.parameters['tags'] = self.tags
416 response = self.create_update_sqlserver()
417 response.pop('administrator_login_password', None)
418
419 if not old_response:
420 self.results['changed'] = True
421 else:
422 self.results['changed'] = True if self.change_admin_password else old_response.__ne__(response)
423 self.log("Creation / Update done")
424 elif self.to_do == Actions.Delete:
425 self.log("SQL Server instance deleted")
426 self.results['changed'] = True
427
428 if self.check_mode:
429 return self.results
430
431 self.delete_sqlserver()
432 # make sure instance is actually deleted, for some Azure resources, instance is hanging around
433 # for some time after deletion -- this should be really fixed in Azure
434 while self.get_sqlserver():
435 time.sleep(20)
436 else:
437 self.log("SQL Server instance unchanged")
438 self.results['changed'] = False
439 response = old_response
440
441 if response:
442 self.results.update(self.format_results(response))
443
444 return self.results
445
446 def create_update_sqlserver(self):
447 '''
448 Creates or updates SQL Server with the specified configuration.
449
450 :return: deserialized SQL Server instance state dictionary
451 '''
452 self.log("Creating / Updating the SQL Server instance {0}".format(self.name))
453
454 try:
455 response = self.sql_client.servers.begin_create_or_update(resource_group_name=self.resource_group,
456 server_name=self.name,
457 parameters=self.parameters)
458 if isinstance(response, LROPoller):
459 response = self.get_poller_result(response)
460
461 except Exception as exc:
462 self.log('Error attempting to create the SQL Server instance.')
463 self.fail("Error creating the SQL Server instance: {0}".format(str(exc)))
464 return response.as_dict()
465
466 def delete_sqlserver(self):
467 '''
468 Deletes specified SQL Server instance in the specified subscription and resource group.
469
470 :return: True
471 '''
472 self.log("Deleting the SQL Server instance {0}".format(self.name))
473 try:
474 response = self.sql_client.servers.begin_delete(resource_group_name=self.resource_group,
475 server_name=self.name)
476 if isinstance(response, LROPoller):
477 response = self.get_poller_result(response)
478 except Exception as e:
479 self.log('Error attempting to delete the SQL Server instance.')
480 self.fail("Error deleting the SQL Server instance: {0}".format(str(e)))
481
482 return True
483
484 def get_sqlserver(self):
485 '''
486 Gets the properties of the specified SQL Server.
487
488 :return: deserialized SQL Server instance state dictionary
489 '''
490 self.log("Checking if the SQL Server instance {0} is present".format(self.name))
491 found = False
492 try:
493 response = self.sql_client.servers.get(resource_group_name=self.resource_group,
494 server_name=self.name)
495 found = True
496 self.log("Response : {0}".format(response))
497 self.log("SQL Server instance : {0} found".format(response.name))
498 except ResourceNotFoundError:
499 self.log('Did not find the SQL Server instance.')
500 if found is True:
501 return response.as_dict()
502
503 return False
504
505 def format_results(self, response):
506 return {
507 "id": response.get("id"),
508 "version": response.get("version"),
509 "state": response.get("state"),
510 "fully_qualified_domain_name": response.get("fully_qualified_domain_name"),
511 }
512
513
514 def main():
515 """Main execution"""
516 AzureRMSqlServer()
517
518
519 if __name__ == '__main__':
520 main()