Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2021 Praveen Ghuge (@praveenghuge), Karl Dasan (@karldas30)
4 #
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6 from __future__ import absolute_import, division, print_function
7 __metaclass__ = type
8
9 DOCUMENTATION = '''
10 ---
11 module: azure_rm_notificationhub
12 version_added: "1.7.0"
13 short_description: Manage Notification Hub
14 description:
15 - Create, update and delete instance of Notification Hub.
16 options:
17 resource_group:
18 description:
19 - Name of the resource group to which the resource belongs.
20 required: True
21 type: str
22 namespace_name:
23 description:
24 - Name of the namespace in which to create notification hub.
25 required: True
26 type: str
27 name:
28 description:
29 - Unique name of the Notification Hub.
30 type: str
31 location:
32 description:
33 - Resource location. If not set, location from the resource group will be used as default.
34 type: str
35 sku:
36 description:
37 - The name of the SKU.
38 - Please see L(https://azure.microsoft.com/en-in/pricing/details/notification-hubs/,).
39 default: free
40 choices:
41 - free
42 - basic
43 - standard
44 type: str
45 state:
46 description:
47 - Assert the state of the Notification Hub.
48 - Use C(present) to create or update an notification hub and C(absent) to delete it.
49 default: present
50 choices:
51 - absent
52 - present
53 type: str
54 extends_documentation_fragment:
55 - azure.azcollection.azure
56 - azure.azcollection.azure_tags
57
58 author:
59 - Praveen Ghuge (@praveenghuge)
60 - Karl Dasan (@karldas30)
61 '''
62 EXAMPLES = '''
63
64 - name: "Create Notification Hub"
65 azure_rm_notificationhub:
66 resource_group: testgroupans
67 location: eastus
68 namespace_name: myNamespace
69 name: myhub
70 tags:
71 - a: b
72 sku: free
73
74 - name: Delete Notification Hub
75 azure_rm_notificationhub:
76 resource_group: testgroupans
77 name: myNamespace
78 state: absent
79
80 - name: "Create Notification Hub Namespace"
81 azure_rm_notificationhub:
82 resource_group: testgroupans
83 location: eastus
84 namespace_name: myNamespace
85 tags:
86 - a: b
87 sku: free
88
89 - name: Delete Notification Hub Namespace
90 azure_rm_notificationhub:
91 resource_group: testgroupans
92 namespace_name: myNamespace
93 state: absent
94 '''
95
96 RETURN = '''
97 state:
98 description:
99 - Current state of the Notification Hub namesapce or Notification Hub.
100 returned: always
101 type: dict
102 sample: {
103 "additional_properties": {},
104 "critical": false,
105 "data_center": null,
106 "enabled": true,
107 "location": "eastus2",
108 "metric_id": null,
109 "name": "testnaedd3d22d3w",
110 "namespace_type": "NotificationHub",
111 "provisioning_state": "Succeeded",
112 "region": null,
113 "scale_unit": null,
114 "service_bus_endpoint": "https://testnaedd3d22d3w.servicebus.windows.net:443/",
115 "sku": { "name":"Free" },
116 "tags": {
117 "a": "b"
118 },
119 "type": "Microsoft.NotificationHubs/namespaces"
120 }
121 '''
122
123 import time
124 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
125
126 try:
127 from azure.core.exceptions import ResourceNotFoundError
128 from azure.mgmt.notificationhubs.models import NotificationHubCreateOrUpdateParameters, NamespaceCreateOrUpdateParameters
129 from azure.mgmt.notificationhubs.models import Sku
130 except ImportError:
131 # This is handled in azure_rm_common
132 pass
133
134
135 class AzureNotificationHub(AzureRMModuleBase):
136
137 def __init__(self):
138 # define user inputs from playbook
139
140 self.module_arg_spec = dict(
141 resource_group=dict(type='str', required=True),
142 namespace_name=dict(type='str', required=True),
143 name=dict(type='str'),
144 location=dict(type='str'),
145 sku=dict(type='str', choices=[
146 'free', 'basic', 'standard'], default='free'),
147 state=dict(choices=['present', 'absent'],
148 default='present', type='str'),
149 )
150
151 self.resource_group = None
152 self.namespace_name = None
153 self.name = None
154 self.sku = None
155 self.location = None
156 self.authorizations = None
157 self.tags = None
158 self.state = None
159 self.results = dict(
160 changed=False,
161 state=dict()
162 )
163
164 super(AzureNotificationHub, self).__init__(derived_arg_spec=self.module_arg_spec,
165 supports_check_mode=True,
166 supports_tags=True)
167
168 def exec_module(self, **kwargs):
169
170 for key in list(self.module_arg_spec.keys()) + ['tags']:
171 setattr(self, key, kwargs[key])
172
173 self.results['check_mode'] = self.check_mode
174
175 # retrieve resource group to make sure it exists
176 resource_group = self.get_resource_group(self.resource_group)
177 if not self.location:
178 # Set default location
179 self.location = resource_group.location
180
181 results = dict()
182 changed = False
183
184 try:
185 self.log(
186 'Fetching Notification Hub Namespace {0}'.format(self.name))
187 namespace = self.notification_hub_client.namespaces.get(
188 self.resource_group, self.namespace_name)
189
190 results = namespace_to_dict(namespace)
191 if self.name:
192 self.log('Fetching Notification Hub {0}'.format(self.name))
193 notification_hub = self.notification_hub_client.notification_hubs.get(
194 self.resource_group, self.namespace_name, self.name)
195 results = notification_hub_to_dict(
196 notification_hub)
197 # don't change anything if creating an existing namespace, but change if deleting it
198 if self.state == 'present':
199 changed = False
200
201 update_tags, results['tags'] = self.update_tags(
202 results['tags'])
203
204 if update_tags:
205 changed = True
206 elif self.namespace_name and not self.name:
207 if self.sku != results['sku']['name'].lower():
208 changed = True
209
210 elif self.state == 'absent':
211 changed = True
212
213 except ResourceNotFoundError:
214 # the notification hub does not exist so create it
215 if self.state == 'present':
216 changed = True
217 else:
218 # you can't delete what is not there
219 changed = False
220
221 self.results['changed'] = changed
222 if self.name and not changed:
223 self.results['state'] = results
224
225 # return the results if your only gathering information
226 if self.check_mode:
227 return self.results
228
229 if changed:
230 if self.state == "present":
231 if self.name is None:
232 self.results['state'] = self.create_or_update_namespaces()
233 elif self.namespace_name and self.name:
234 self.results['state'] = self.create_or_update_notification_hub()
235 elif self.state == "absent":
236 # delete Notification Hub
237 if self.name is None:
238 self.delete_namespace()
239 elif self.namespace_name and self.name:
240 self.delete_notification_hub()
241 self.results['state']['status'] = 'Deleted'
242
243 return self.results
244
245 def create_or_update_namespaces(self):
246 '''
247 create or update namespaces
248 '''
249 try:
250 namespace_params = NamespaceCreateOrUpdateParameters(
251 location=self.location,
252 namespace_type="NotificationHub",
253 sku=Sku(name=self.sku),
254 tags=self.tags
255 )
256 result = self.notification_hub_client.namespaces.create_or_update(
257 self.resource_group,
258 self.namespace_name,
259 namespace_params)
260
261 namespace = self.notification_hub_client.namespaces.get(
262 self.resource_group,
263 self.namespace_name)
264
265 while namespace.status == "Created":
266 time.sleep(30)
267 namespace = self.notification_hub_client.namespaces.get(
268 self.resource_group,
269 self.namespace_name,
270 )
271 except Exception as ex:
272 self.fail("Failed to create namespace {0} in resource group {1}: {2}".format(
273 self.namespace_name, self.resource_group, str(ex)))
274 return namespace_to_dict(result)
275
276 def create_or_update_notification_hub(self):
277 '''
278 Create or update Notification Hub.
279 :return: create or update Notification Hub instance state dictionary
280 '''
281 try:
282 response = self.create_or_update_namespaces()
283 params = NotificationHubCreateOrUpdateParameters(
284 location=self.location,
285 sku=Sku(name=self.sku),
286 tags=self.tags
287 )
288 result = self.notification_hub_client.notification_hubs.create_or_update(
289 self.resource_group,
290 self.namespace_name,
291 self.name,
292 params)
293 self.log("Response : {0}".format(result))
294 except Exception as ex:
295 self.fail("Failed to create notification hub {0} in resource group {1}: {2}".format(
296 self.name, self.resource_group, str(ex)))
297 return notification_hub_to_dict(result)
298
299 def delete_notification_hub(self):
300 '''
301 Deletes specified notication hub
302 :return True
303 '''
304 self.log("Deleting the notification hub {0}".format(self.name))
305 try:
306 result = self.notification_hub_client.notification_hubs.delete(
307 self.resource_group, self.namespace_name, self.name)
308 except Exception as e:
309 self.log('Error attempting to delete notification hub.')
310 self.fail(
311 "Error deleting the notification hub : {0}".format(str(e)))
312 return True
313
314 def delete_namespace(self):
315 '''
316 Deletes specified namespace
317 :return True
318 '''
319 self.log("Deleting the namespace {0}".format(self.namespace_name))
320 try:
321 result = self.notification_hub_client.namespaces.begin_delete(
322 self.resource_group, self.namespace_name)
323 except Exception as e:
324 self.log('Error attempting to delete namespace.')
325 self.fail(
326 "Error deleting the namespace : {0}".format(str(e)))
327 return True
328
329
330 def notification_hub_to_dict(item):
331 # turn notification hub object into a dictionary (serialization)
332 notification_hub = item.as_dict()
333 result = dict(
334 additional_properties=notification_hub.get(
335 'additional_properties', {}),
336 id=notification_hub.get('id', None),
337 name=notification_hub.get('name', None),
338 type=notification_hub.get('type', None),
339 location=notification_hub.get(
340 'location', '').replace(' ', '').lower(),
341 tags=notification_hub.get('tags', None),
342 provisioning_state=notification_hub.get(
343 'provisioning_state', None),
344 region=notification_hub.get('region', None),
345 metric_id=notification_hub.get('metric_id', None),
346 service_bus_endpoint=notification_hub.get(
347 'service_bus_endpoint', None),
348 scale_unit=notification_hub.get('scale_unit', None),
349 enabled=notification_hub.get('enabled', None),
350 critical=notification_hub.get('critical', None),
351 data_center=notification_hub.get('data_center', None),
352 namespace_type=notification_hub.get('namespace_type', None)
353 )
354 return result
355
356
357 def namespace_to_dict(item):
358 # turn notification hub namespace object into a dictionary (serialization)
359 namespace = item.as_dict()
360 result = dict(
361 additional_properties=namespace.get(
362 'additional_properties', {}),
363 name=namespace.get('name', None),
364 type=namespace.get('type', None),
365 location=namespace.get(
366 'location', '').replace(' ', '').lower(),
367 sku=namespace.get("sku"),
368 tags=namespace.get('tags', None),
369 provisioning_state=namespace.get(
370 'provisioning_state', None),
371 region=namespace.get('region', None),
372 metric_id=namespace.get('metric_id', None),
373 service_bus_endpoint=namespace.get(
374 'service_bus_endpoint', None),
375 scale_unit=namespace.get('scale_unit', None),
376 enabled=namespace.get('enabled', None),
377 critical=namespace.get('critical', None),
378 data_center=namespace.get('data_center', None),
379 namespace_type=namespace.get('namespace_type', None)
380 )
381 return result
382
383
384 def main():
385 AzureNotificationHub()
386
387
388 if __name__ == '__main__':
389 main()