Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2018 Yuwei Zhou, <[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_servicebus_info
14
15 version_added: "0.1.2"
16
17 short_description: Get servicebus facts
18
19 description:
20 - Get facts for a specific servicebus or all servicebus in a resource group or subscription.
21
22 options:
23 name:
24 description:
25 - Limit results to a specific servicebus.
26 type: str
27 resource_group:
28 description:
29 - Limit results in a specific resource group.
30 type: str
31 tags:
32 description:
33 - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'.
34 type: list
35 elements: str
36 namespace:
37 description:
38 - Servicebus namespace name.
39 - A namespace is a scoping container for all messaging components.
40 - Multiple queues and topics can reside within a single namespace, and namespaces often serve as application containers.
41 - Required when I(type=namespace).
42 type: str
43 type:
44 description:
45 - Type of the resource.
46 type: str
47 required: true
48 choices:
49 - namespace
50 - queue
51 - topic
52 - subscription
53 topic:
54 description:
55 - Topic name.
56 - Required when I(type=subscription).
57 type: str
58 show_sas_policies:
59 description:
60 - Whether to show the SAS policies.
61 - Not support when I(type=subscription).
62 - Note if enable this option, the facts module will raise two more HTTP call for each resources, need more network overhead.
63 type: bool
64 extends_documentation_fragment:
65 - azure.azcollection.azure
66
67 author:
68 - Yuwei Zhou (@yuwzho)
69
70 '''
71
72 EXAMPLES = '''
73 - name: Get all namespaces under a resource group
74 azure_rm_servicebus_info:
75 resource_group: myResourceGroup
76 type: namespace
77
78 - name: Get all topics under a namespace
79 azure_rm_servicebus_info:
80 resource_group: myResourceGroup
81 namespace: bar
82 type: topic
83
84 - name: Get a single queue with SAS policies
85 azure_rm_servicebus_info:
86 resource_group: myResourceGroup
87 namespace: bar
88 type: queue
89 name: sbqueue
90 show_sas_policies: true
91
92 - name: Get all subscriptions under a resource group
93 azure_rm_servicebus_info:
94 resource_group: myResourceGroup
95 type: subscription
96 namespace: bar
97 topic: sbtopic
98 '''
99 RETURN = '''
100 servicebuses:
101 description:
102 - List of servicebus dicts.
103 returned: always
104 type: complex
105 contains:
106 id:
107 description:
108 - Resource ID.
109 returned: always
110 type: str
111 sample: "/subscriptions/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/resourceGroups/foo/providers/Microsoft.ServiceBus/
112 namespaces/bar/topics/baz/subscriptions/qux"
113 name:
114 description:
115 - Resource name.
116 returned: always
117 type: str
118 sample: qux
119 location:
120 description:
121 - The Geo-location where the resource lives.
122 returned: always
123 type: str
124 sample: eastus
125 namespace:
126 description:
127 - I(namespace) name of the C(queue) or C(topic), C(subscription).
128 returned: always
129 type: str
130 sample: bar
131 topic:
132 description:
133 - Topic name of a subscription.
134 returned: always
135 type: str
136 sample: baz
137 tags:
138 description:
139 - Resource tags.
140 returned: always
141 type: dict
142 sample: {env: sandbox}
143 sku:
144 description:
145 - Properties of namespace's SKU.
146 returned: always
147 type: str
148 sample: Standard
149 provisioning_state:
150 description:
151 - Provisioning state of the namespace.
152 returned: always
153 type: str
154 sample: Succeeded
155 service_bus_endpoint:
156 description:
157 - Endpoint you can use to perform Service Bus operations.
158 returned: always
159 type: str
160 sample: "https://bar.servicebus.windows.net:443/"
161 metric_id:
162 description:
163 - Identifier for Azure Insights metrics of namespace.
164 returned: always
165 type: str
166 sample: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX:bar"
167 type:
168 description:
169 - Resource type.
170 - Namespace is a scoping container for all messaging components.
171 - Queue enables you to store messages until the receiving application is available to receive and process them.
172 - Topic and subscriptions enable 1:n relationships between publishers and subscribers.
173 returned: always
174 type: str
175 sample: "Microsoft.ServiceBus/Namespaces/Topics"
176 created_at:
177 description:
178 - Exact time the message was created.
179 returned: always
180 type: str
181 sample: "2019-01-25 02:46:55.543953+00:00"
182 updated_at:
183 description:
184 - The exact time the message was updated.
185 returned: always
186 type: str
187 sample: "2019-01-25 02:46:55.543953+00:00"
188 accessed_at:
189 description:
190 - Last time the message was sent, or a request was received for this topic.
191 returned: always
192 type: str
193 sample: "2019-01-25 02:46:55.543953+00:00"
194 subscription_count:
195 description:
196 - Number of subscriptions under a topic.
197 returned: always
198 type: int
199 sample: 1
200 count_details:
201 description:
202 - Message count details.
203 returned: always
204 type: complex
205 contains:
206 active_message_count:
207 description:
208 - Number of active messages in the C(queue), C(topic), or C(subscription).
209 returned: always
210 type: int
211 sample: 0
212 dead_letter_message_count:
213 description:
214 - Number of messages that are dead lettered.
215 returned: always
216 type: int
217 sample: 0
218 scheduled_message_count:
219 description:
220 - Number of scheduled messages.
221 returned: always
222 type: int
223 sample: 0
224 transfer_message_count:
225 description:
226 - Number of messages transferred to another C(queue), C(topic), or C(subscription).
227 returned: always
228 type: int
229 sample: 0
230 transfer_dead_letter_message_count:
231 description:
232 - Number of messages transferred into dead letters.
233 returned: always
234 type: int
235 sample: 0
236 support_ordering:
237 description:
238 - Value that indicates whether the C(topic) supports ordering.
239 returned: always
240 type: bool
241 sample: true
242 status:
243 description:
244 - The status of a messaging entity.
245 returned: always
246 type: str
247 sample: active
248 requires_session:
249 description:
250 - A value that indicates whether the C(queue) or C(topic) supports the concept of sessions.
251 returned: always
252 type: bool
253 sample: true
254 requires_duplicate_detection:
255 description:
256 - A value indicating if this C(queue) or C(topic) requires duplicate detection.
257 returned: always
258 type: bool
259 sample: true
260 max_size_in_mb:
261 description:
262 - Maximum size of the C(queue) or C(topic) in megabytes, which is the size of the memory allocated for the C(topic).
263 returned: always
264 type: int
265 sample: 5120
266 max_delivery_count:
267 description:
268 - The maximum delivery count.
269 - A message is automatically deadlettered after this number of deliveries.
270 returned: always
271 type: int
272 sample: 10
273 lock_duration_in_seconds:
274 description:
275 - ISO 8601 timespan duration of a peek-lock.
276 - The amount of time that the message is locked for other receivers.
277 - The maximum value for LockDuration is 5 minutes.
278 returned: always
279 type: int
280 sample: 60
281 forward_to:
282 description:
283 - C(queue) or C(topic) name to forward the messages.
284 returned: always
285 type: str
286 sample: quux
287 forward_dead_lettered_messages_to:
288 description:
289 - C(queue) or C(topic) name to forward the Dead Letter message.
290 returned: always
291 type: str
292 sample: corge
293 enable_partitioning:
294 description:
295 - Value that indicates whether the C(queue) or C(topic) to be partitioned across multiple message brokers is enabled.
296 returned: always
297 type: bool
298 sample: true
299 enable_express:
300 description:
301 - Value that indicates whether Express Entities are enabled.
302 - An express topic holds a message in memory temporarily before writing it to persistent storage.
303 returned: always
304 type: bool
305 sample: true
306 enable_batched_operations:
307 description:
308 - Value that indicates whether server-side batched operations are enabled.
309 returned: always
310 type: bool
311 sample: true
312 duplicate_detection_time_in_seconds:
313 description:
314 - ISO 8601 timeSpan structure that defines the duration of the duplicate detection history.
315 returned: always
316 type: int
317 sample: 600
318 default_message_time_to_live_seconds:
319 description:
320 - ISO 8061 Default message timespan to live value.
321 - This is the duration after which the message expires, starting from when the message is sent to Service Bus.
322 - This is the default value used when TimeToLive is not set on a message itself.
323 returned: always
324 type: int
325 sample: 0
326 dead_lettering_on_message_expiration:
327 description:
328 - A value that indicates whether this C(queue) or C(topic) has dead letter support when a message expires.
329 returned: always
330 type: int
331 sample: 0
332 dead_lettering_on_filter_evaluation_exceptions:
333 description:
334 - Value that indicates whether a subscription has dead letter support on filter evaluation exceptions.
335 returned: always
336 type: int
337 sample: 0
338 auto_delete_on_idle_in_seconds:
339 description:
340 - ISO 8061 timeSpan idle interval after which the queue or topic is automatically deleted.
341 - The minimum duration is 5 minutes.
342 returned: always
343 type: int
344 sample: true
345 size_in_bytes:
346 description:
347 - The size of the C(queue) or C(topic) in bytes.
348 returned: always
349 type: int
350 sample: 0
351 message_count:
352 description:
353 - Number of messages.
354 returned: always
355 type: int
356 sample: 10
357 sas_policies:
358 description:
359 - Dict of SAS policies.
360 - Will not be returned until I(show_sas_policy) set.
361 returned: always
362 type: dict
363 sample: {
364 "testpolicy1": {
365 "id": "/subscriptions/XXXXXXXX-XXXX-XXXX-XXXXXXXXXXXX/resourceGroups/
366 foo/providers/Microsoft.ServiceBus/namespaces/bar/queues/qux/authorizationRules/testpolicy1",
367 "keys": {
368 "key_name": "testpolicy1",
369 "primary_connection_string": "Endpoint=sb://bar.servicebus.windows.net/;
370 SharedAccessKeyName=testpolicy1;SharedAccessKey=XXXXXXXXXXXXXXXXX;EntityPath=qux",
371 "primary_key": "XXXXXXXXXXXXXXXXX",
372 "secondary_connection_string": "Endpoint=sb://bar.servicebus.windows.net/;
373 SharedAccessKeyName=testpolicy1;SharedAccessKey=XXXXXXXXXXXXXXX;EntityPath=qux",
374 "secondary_key": "XXXXXXXXXXXXXXX"
375 },
376 "name": "testpolicy1",
377 "rights": "listen_send",
378 "type": "Microsoft.ServiceBus/Namespaces/Queues/AuthorizationRules"
379 }
380 }
381 private_endpoint_connections:
382 description:
383 - Properties of the PrivateEndpointConnection.
384 type: list
385 returned: always
386 sample: [{
387 "id": "/subscriptions/xxxxxx/resourceGroups/myRG/providers/Microsoft.ServiceBus/namespaces/fredVM/privateEndpointConnections/xxxxxxxx",
388 "name": "xxxxxx",
389 "private_endpoint": {
390 "id": "/subscriptions/xxxxx/resourceGroups/myRG/providers/Microsoft.Network/privateEndpoints/fredprivateendpoint"
391 },
392 "private_link_service_connection_state": {
393 "description": "Auto-Approved",
394 "status": "Approved"
395 },
396 "provisioning_state": "Succeeded",
397 "type": "Microsoft.ServiceBus/Namespaces/PrivateEndpointConnections"
398 }]
399
400 '''
401
402 try:
403 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
404 from azure.mgmt.servicebus.v2022_10_01_preview.models import Identity
405 except Exception:
406 # This is handled in azure_rm_common
407 pass
408 from ansible.module_utils.common.dict_transformations import _camel_to_snake
409 from ansible.module_utils._text import to_native
410 from datetime import datetime, timedelta
411
412 duration_spec_map = dict(
413 default_message_time_to_live='default_message_time_to_live_seconds',
414 duplicate_detection_history_time_window='duplicate_detection_time_in_seconds',
415 auto_delete_on_idle='auto_delete_on_idle_in_seconds',
416 lock_duration='lock_duration_in_seconds'
417 )
418
419
420 def is_valid_timedelta(value):
421 if value == timedelta(10675199, 10085, 477581):
422 return None
423 return value
424
425
426 class AzureRMServiceBusInfo(AzureRMModuleBase):
427
428 def __init__(self):
429
430 self.module_arg_spec = dict(
431 name=dict(type='str'),
432 resource_group=dict(type='str'),
433 tags=dict(type='list', elements='str'),
434 type=dict(type='str', required=True, choices=['namespace', 'topic', 'queue', 'subscription']),
435 namespace=dict(type='str'),
436 topic=dict(type='str'),
437 show_sas_policies=dict(type='bool')
438 )
439
440 required_if = [
441 ('type', 'subscription', ['topic', 'resource_group', 'namespace']),
442 ('type', 'topic', ['resource_group', 'namespace']),
443 ('type', 'queue', ['resource_group', 'namespace'])
444 ]
445
446 self.results = dict(
447 changed=False,
448 servicebuses=[]
449 )
450
451 self.name = None
452 self.resource_group = None
453 self.tags = None
454 self.type = None
455 self.namespace = None
456 self.topic = None
457 self.show_sas_policies = None
458
459 super(AzureRMServiceBusInfo, self).__init__(self.module_arg_spec,
460 supports_check_mode=True,
461 supports_tags=False,
462 required_if=required_if,
463 facts_module=True)
464
465 def exec_module(self, **kwargs):
466
467 for key in self.module_arg_spec:
468 setattr(self, key, kwargs[key])
469
470 response = []
471 if self.name:
472 response = self.get_item()
473 elif self.resource_group:
474 response = self.list_items()
475 else:
476 response = self.list_all_items()
477
478 self.results['servicebuses'] = [self.instance_to_dict(x) for x in response]
479 return self.results
480
481 def instance_to_dict(self, instance):
482 result = dict()
483 instance_type = getattr(self.servicebus_models, 'SB{0}'.format(str.capitalize(self.type)))
484 attribute_map = instance_type._attribute_map
485 for attribute in attribute_map.keys():
486 value = getattr(instance, attribute)
487 if attribute_map[attribute]['type'] == 'duration':
488 if is_valid_timedelta(value):
489 key = duration_spec_map.get(attribute) or attribute
490 result[key] = int(value.total_seconds())
491 elif attribute == 'status':
492 result['status'] = _camel_to_snake(value)
493 elif isinstance(value, self.servicebus_models.MessageCountDetails):
494 result[attribute] = value.as_dict()
495 elif isinstance(value, self.servicebus_models.SBSku):
496 result[attribute] = value.name.lower()
497 elif isinstance(value, datetime):
498 result[attribute] = str(value)
499 elif isinstance(value, Identity):
500 result['identity'] = value.as_dict()
501 elif isinstance(value, str):
502 result[attribute] = to_native(value)
503 elif attribute == 'max_size_in_megabytes':
504 result['max_size_in_mb'] = value
505 elif attribute == 'private_endpoint_connections' and isinstance(value, list):
506 result['private_endpoint_connections'] = [item.as_dict() for item in value]
507 else:
508 result[attribute] = value
509 if self.show_sas_policies and self.type != 'subscription':
510 policies = self.get_auth_rules()
511 for name in policies.keys():
512 policies[name]['keys'] = self.get_sas_key(name)
513 result['sas_policies'] = policies
514 if self.namespace:
515 result['namespace'] = self.namespace
516 if self.topic:
517 result['topic'] = self.topic
518 return result
519
520 def _get_client(self):
521 return getattr(self.servicebus_client, '{0}s'.format(self.type))
522
523 def get_item(self):
524 try:
525 client = self._get_client()
526 if self.type == 'namespace':
527 item = client.get(self.resource_group, self.name)
528 return [item] if self.has_tags(item.tags, self.tags) else []
529 elif self.type == 'subscription':
530 return [client.get(self.resource_group, self.namespace, self.topic, self.name)]
531 else:
532 return [client.get(self.resource_group, self.namespace, self.name)]
533 except Exception:
534 pass
535 return []
536
537 def list_items(self):
538 try:
539 client = self._get_client()
540 if self.type == 'namespace':
541 response = client.list_by_resource_group(self.resource_group)
542 return [x for x in response if self.has_tags(x.tags, self.tags)]
543 elif self.type == 'subscription':
544 return client.list_by_topic(self.resource_group, self.namespace, self.topic)
545 else:
546 return client.list_by_namespace(self.resource_group, self.namespace)
547 except Exception as exc:
548 self.fail("Failed to list items - {0}".format(str(exc)))
549 return []
550
551 def list_all_items(self):
552 self.log("List all items in subscription")
553 try:
554 if self.type != 'namespace':
555 return []
556 response = self.servicebus_client.namespaces.list()
557 return [x for x in response if self.has_tags(x.tags, self.tags)]
558 except Exception as exc:
559 self.fail("Failed to list all items - {0}".format(str(exc)))
560 return []
561
562 def get_auth_rules(self):
563 result = dict()
564 try:
565 client = self._get_client()
566 if self.type == 'namespace':
567 rules = client.list_authorization_rules(self.resource_group, self.name)
568 else:
569 rules = client.list_authorization_rules(self.resource_group, self.namespace, self.name)
570 while True:
571 rule = rules.next()
572 result[rule.name] = self.policy_to_dict(rule)
573 except StopIteration:
574 pass
575 except Exception as exc:
576 self.fail('Error when getting SAS policies for {0} {1}: {2}'.format(self.type, self.name, exc.message or str(exc)))
577 return result
578
579 def get_sas_key(self, name):
580 try:
581 client = self._get_client()
582 if self.type == 'namespace':
583 return client.list_keys(self.resource_group, self.name, name).as_dict()
584 else:
585 return client.list_keys(self.resource_group, self.namespace, self.name, name).as_dict()
586 except Exception as exc:
587 self.fail('Error when getting SAS policy {0}\'s key - {1}'.format(name, exc.message or str(exc)))
588 return None
589
590 def policy_to_dict(self, rule):
591 result = rule.as_dict()
592 rights = result['rights']
593 if 'Manage' in rights:
594 result['rights'] = 'manage'
595 elif 'Listen' in rights and 'Send' in rights:
596 result['rights'] = 'listen_send'
597 else:
598 result['rights'] = rights[0].lower()
599 return result
600
601
602 def main():
603 AzureRMServiceBusInfo()
604
605
606 if __name__ == '__main__':
607 main()