Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_mysqldatabase.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_mysqldatabase
14 version_added: "0.1.2"
15 short_description: Manage MySQL Database instance
16 description:
17 - Create, update and delete instance of MySQL 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.
33 required: True
34 type: str
35 charset:
36 description:
37 - The charset of the database. Check MySQL documentation for possible values.
38 - This is only set on creation, use I(force_update) to recreate a database if the values don't match.
39 type: str
40 collation:
41 description:
42 - The collation of the database. Check MySQL documentation for possible values.
43 - This is only set on creation, use I(force_update) to recreate a database if the values don't match.
44 type: str
45 force_update:
46 description:
47 - When set to C(true), will delete and recreate the existing MySQL database if any of the properties don't match what is set.
48 - When set to C(false), no change will occur to the database even if any of the properties do not match.
49 type: bool
50 default: 'no'
51 state:
52 description:
53 - Assert the state of the MySQL Database. Use C(present) to create or update a database and C(absent) to delete it.
54 default: present
55 type: str
56 choices:
57 - absent
58 - present
59
60 extends_documentation_fragment:
61 - azure.azcollection.azure
62
63 author:
64 - Zim Kalinowski (@zikalino)
65
66 '''
67
68 EXAMPLES = '''
69 - name: Create (or update) MySQL Database
70 azure_rm_mysqldatabase:
71 resource_group: myResourceGroup
72 server_name: testserver
73 name: db1
74 '''
75
76 RETURN = '''
77 id:
78 description:
79 - Resource ID.
80 returned: always
81 type: str
82 sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DBforMySQL/servers/testserver/databases/db1
83 name:
84 description:
85 - Resource name.
86 returned: always
87 type: str
88 sample: db1
89 '''
90
91 import time
92
93 try:
94 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
95 from azure.core.exceptions import ResourceNotFoundError, HttpResponseError
96 from azure.core.polling import LROPoller
97 except ImportError:
98 # This is handled in azure_rm_common
99 pass
100
101
102 class Actions:
103 NoAction, Create, Update, Delete = range(4)
104
105
106 class AzureRMMySqlDatabase(AzureRMModuleBase):
107 """Configuration class for an Azure RM MySQL Database resource"""
108
109 def __init__(self):
110 self.module_arg_spec = dict(
111 resource_group=dict(
112 type='str',
113 required=True
114 ),
115 server_name=dict(
116 type='str',
117 required=True
118 ),
119 name=dict(
120 type='str',
121 required=True
122 ),
123 charset=dict(
124 type='str'
125 ),
126 collation=dict(
127 type='str'
128 ),
129 force_update=dict(
130 type='bool',
131 default=False
132 ),
133 state=dict(
134 type='str',
135 default='present',
136 choices=['present', 'absent']
137 )
138 )
139
140 self.resource_group = None
141 self.server_name = None
142 self.name = None
143 self.force_update = None
144 self.parameters = dict()
145
146 self.results = dict(changed=False)
147 self.state = None
148 self.to_do = Actions.NoAction
149
150 super(AzureRMMySqlDatabase, self).__init__(derived_arg_spec=self.module_arg_spec,
151 supports_check_mode=True,
152 supports_tags=False)
153
154 def exec_module(self, **kwargs):
155 """Main module execution method"""
156
157 for key in list(self.module_arg_spec.keys()):
158 if hasattr(self, key):
159 setattr(self, key, kwargs[key])
160 elif kwargs[key] is not None:
161 if key == "charset":
162 self.parameters["charset"] = kwargs[key]
163 elif key == "collation":
164 self.parameters["collation"] = kwargs[key]
165
166 old_response = None
167 response = None
168
169 resource_group = self.get_resource_group(self.resource_group)
170
171 old_response = self.get_mysqldatabase()
172
173 if not old_response:
174 self.log("MySQL Database instance doesn't exist")
175 if self.state == 'absent':
176 self.log("Old instance didn't exist")
177 else:
178 self.to_do = Actions.Create
179 else:
180 self.log("MySQL Database instance already exists")
181 if self.state == 'absent':
182 self.to_do = Actions.Delete
183 elif self.state == 'present':
184 self.log("Need to check if MySQL Database instance has to be deleted or may be updated")
185 if ('collation' in self.parameters) and (self.parameters['collation'] != old_response['collation']):
186 self.to_do = Actions.Update
187 if ('charset' in self.parameters) and (self.parameters['charset'] != old_response['charset']):
188 self.to_do = Actions.Update
189 if self.to_do == Actions.Update:
190 if self.force_update:
191 if not self.check_mode:
192 self.delete_mysqldatabase()
193 else:
194 self.fail("Database properties cannot be updated without setting 'force_update' option")
195 self.to_do = Actions.NoAction
196
197 if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
198 self.log("Need to Create / Update the MySQL Database instance")
199
200 if self.check_mode:
201 self.results['changed'] = True
202 return self.results
203
204 response = self.create_update_mysqldatabase()
205 self.results['changed'] = True
206 self.log("Creation / Update done")
207 elif self.to_do == Actions.Delete:
208 self.log("MySQL Database instance deleted")
209 self.results['changed'] = True
210
211 if self.check_mode:
212 return self.results
213
214 self.delete_mysqldatabase()
215 # make sure instance is actually deleted, for some Azure resources, instance is hanging around
216 # for some time after deletion -- this should be really fixed in Azure
217 while self.get_mysqldatabase():
218 time.sleep(20)
219 else:
220 self.log("MySQL Database instance unchanged")
221 self.results['changed'] = False
222 response = old_response
223
224 if response:
225 self.results["id"] = response["id"]
226 self.results["name"] = response["name"]
227
228 return self.results
229
230 def create_update_mysqldatabase(self):
231 '''
232 Creates or updates MySQL Database with the specified configuration.
233
234 :return: deserialized MySQL Database instance state dictionary
235 '''
236 self.log("Creating / Updating the MySQL Database instance {0}".format(self.name))
237
238 try:
239 response = self.mysql_client.databases.begin_create_or_update(resource_group_name=self.resource_group,
240 server_name=self.server_name,
241 database_name=self.name,
242 parameters=self.parameters)
243 if isinstance(response, LROPoller):
244 response = self.get_poller_result(response)
245
246 except Exception as exc:
247 self.log('Error attempting to create the MySQL Database instance.')
248 self.fail("Error creating the MySQL Database instance: {0}".format(str(exc)))
249 return response.as_dict()
250
251 def delete_mysqldatabase(self):
252 '''
253 Deletes specified MySQL Database instance in the specified subscription and resource group.
254
255 :return: True
256 '''
257 self.log("Deleting the MySQL Database instance {0}".format(self.name))
258 try:
259 response = self.mysql_client.databases.begin_delete(resource_group_name=self.resource_group,
260 server_name=self.server_name,
261 database_name=self.name)
262 except Exception as e:
263 self.log('Error attempting to delete the MySQL Database instance.')
264 self.fail("Error deleting the MySQL Database instance: {0}".format(str(e)))
265
266 return True
267
268 def get_mysqldatabase(self):
269 '''
270 Gets the properties of the specified MySQL Database.
271
272 :return: deserialized MySQL Database instance state dictionary
273 '''
274 self.log("Checking if the MySQL Database instance {0} is present".format(self.name))
275 found = False
276 try:
277 response = self.mysql_client.databases.get(resource_group_name=self.resource_group,
278 server_name=self.server_name,
279 database_name=self.name)
280 found = True
281 self.log("Response : {0}".format(response))
282 self.log("MySQL Database instance : {0} found".format(response.name))
283 except ResourceNotFoundError as e:
284 self.log('Did not find the MySQL Database instance.')
285 except HttpResponseError as e:
286 self.log("Get MySQL Database instance error. code: {0}, message: {1}".format(e.status_code, str(e.error)))
287 if found is True:
288 return response.as_dict()
289
290 return False
291
292
293 def main():
294 """Main execution"""
295 AzureRMMySqlDatabase()
296
297
298 if __name__ == '__main__':
299 main()