Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_postgresqldatabase.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_postgresqldatabase
14 version_added: "0.1.2"
15 short_description: Manage PostgreSQL Database instance
16 description:
17 - Create, update and delete instance of PostgreSQL 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 PostgreSQL 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 PostgreSQL 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 PostgreSQL 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 PostgreSQL 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) PostgreSQL Database
70 azure_rm_postgresqldatabase:
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/myResourceGroups/providers/Microsoft.DBforPostgreSQL/servers/testserve
83 r/databases/db1"
84 name:
85 description:
86 - Resource name.
87 returned: always
88 type: str
89 sample: db1
90 '''
91
92 import time
93
94 try:
95 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
96 from azure.core.exceptions import ResourceNotFoundError
97 from azure.core.polling import LROPoller
98 except ImportError:
99 # This is handled in azure_rm_common
100 pass
101
102
103 class Actions:
104 NoAction, Create, Update, Delete = range(4)
105
106
107 class AzureRMPostgreSqlDatabases(AzureRMModuleBase):
108 """Configuration class for an Azure RM PostgreSQL Database resource"""
109
110 def __init__(self):
111 self.module_arg_spec = dict(
112 resource_group=dict(
113 type='str',
114 required=True
115 ),
116 server_name=dict(
117 type='str',
118 required=True
119 ),
120 name=dict(
121 type='str',
122 required=True
123 ),
124 charset=dict(
125 type='str'
126 ),
127 collation=dict(
128 type='str'
129 ),
130 force_update=dict(
131 type='bool',
132 default=False
133 ),
134 state=dict(
135 type='str',
136 default='present',
137 choices=['present', 'absent']
138 )
139 )
140
141 self.resource_group = None
142 self.server_name = None
143 self.name = None
144 self.force_update = None
145 self.parameters = dict()
146
147 self.results = dict(changed=False)
148 self.state = None
149 self.to_do = Actions.NoAction
150
151 super(AzureRMPostgreSqlDatabases, self).__init__(derived_arg_spec=self.module_arg_spec,
152 supports_check_mode=True,
153 supports_tags=False)
154
155 def exec_module(self, **kwargs):
156 """Main module execution method"""
157
158 for key in list(self.module_arg_spec.keys()):
159 if hasattr(self, key):
160 setattr(self, key, kwargs[key])
161 elif kwargs[key] is not None:
162 if key == "charset":
163 self.parameters["charset"] = kwargs[key]
164 elif key == "collation":
165 self.parameters["collation"] = kwargs[key]
166
167 old_response = None
168 response = None
169
170 resource_group = self.get_resource_group(self.resource_group)
171
172 old_response = self.get_postgresqldatabase()
173
174 if not old_response:
175 self.log("PostgreSQL Database instance doesn't exist")
176 if self.state == 'absent':
177 self.log("Old instance didn't exist")
178 else:
179 self.to_do = Actions.Create
180 else:
181 self.log("PostgreSQL Database instance already exists")
182 if self.state == 'absent':
183 self.to_do = Actions.Delete
184 elif self.state == 'present':
185 self.log("Need to check if PostgreSQL Database instance has to be deleted or may be updated")
186 if ('collation' in self.parameters) and (self.parameters['collation'] != old_response['collation']):
187 self.to_do = Actions.Update
188 if ('charset' in self.parameters) and (self.parameters['charset'] != old_response['charset']):
189 self.to_do = Actions.Update
190 if self.to_do == Actions.Update:
191 if self.force_update:
192 if not self.check_mode:
193 self.delete_postgresqldatabase()
194 else:
195 self.fail("Database properties cannot be updated without setting 'force_update' option")
196 self.to_do = Actions.NoAction
197
198 if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
199 self.log("Need to Create / Update the PostgreSQL Database instance")
200
201 if self.check_mode:
202 self.results['changed'] = True
203 return self.results
204
205 response = self.create_update_postgresqldatabase()
206 self.results['changed'] = True
207 self.log("Creation / Update done")
208 elif self.to_do == Actions.Delete:
209 self.log("PostgreSQL Database instance deleted")
210 self.results['changed'] = True
211
212 if self.check_mode:
213 return self.results
214
215 self.delete_postgresqldatabase()
216 # make sure instance is actually deleted, for some Azure resources, instance is hanging around
217 # for some time after deletion -- this should be really fixed in Azure
218 while self.get_postgresqldatabase():
219 time.sleep(20)
220 else:
221 self.log("PostgreSQL Database instance unchanged")
222 self.results['changed'] = False
223 response = old_response
224
225 if response:
226 self.results["id"] = response["id"]
227 self.results["name"] = response["name"]
228
229 return self.results
230
231 def create_update_postgresqldatabase(self):
232 '''
233 Creates or updates PostgreSQL Database with the specified configuration.
234
235 :return: deserialized PostgreSQL Database instance state dictionary
236 '''
237 self.log("Creating / Updating the PostgreSQL Database instance {0}".format(self.name))
238
239 try:
240 response = self.postgresql_client.databases.begin_create_or_update(resource_group_name=self.resource_group,
241 server_name=self.server_name,
242 database_name=self.name,
243 parameters=self.parameters)
244 if isinstance(response, LROPoller):
245 response = self.get_poller_result(response)
246
247 except Exception as exc:
248 self.log('Error attempting to create the PostgreSQL Database instance.')
249 self.fail("Error creating the PostgreSQL Database instance: {0}".format(str(exc)))
250 return response.as_dict()
251
252 def delete_postgresqldatabase(self):
253 '''
254 Deletes specified PostgreSQL Database instance in the specified subscription and resource group.
255
256 :return: True
257 '''
258 self.log("Deleting the PostgreSQL Database instance {0}".format(self.name))
259 try:
260 response = self.postgresql_client.databases.begin_delete(resource_group_name=self.resource_group,
261 server_name=self.server_name,
262 database_name=self.name)
263 except Exception as e:
264 self.log('Error attempting to delete the PostgreSQL Database instance.')
265 self.fail("Error deleting the PostgreSQL Database instance: {0}".format(str(e)))
266
267 return True
268
269 def get_postgresqldatabase(self):
270 '''
271 Gets the properties of the specified PostgreSQL Database.
272
273 :return: deserialized PostgreSQL Database instance state dictionary
274 '''
275 self.log("Checking if the PostgreSQL Database instance {0} is present".format(self.name))
276 found = False
277 try:
278 response = self.postgresql_client.databases.get(resource_group_name=self.resource_group,
279 server_name=self.server_name,
280 database_name=self.name)
281 found = True
282 self.log("Response : {0}".format(response))
283 self.log("PostgreSQL Database instance : {0} found".format(response.name))
284 except ResourceNotFoundError as e:
285 self.log('Did not find the PostgreSQL Database instance.')
286 if found is True:
287 return response.as_dict()
288
289 return False
290
291
292 def main():
293 """Main execution"""
294 AzureRMPostgreSqlDatabases()
295
296
297 if __name__ == '__main__':
298 main()