Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 from __future__ import absolute_import, division, print_function
6 __metaclass__ = type
7
8
9 DOCUMENTATION = '''
10 ---
11 module: azure_rm_eventgrid_topic
12 version_added: "3.13.0"
13 short_description: Manage Eventgrid Topics
14 description:
15 - Create, update ,delete and replace Eventgrid Topics.
16 options:
17 name:
18 description:
19 - Name of the topic.
20 required: true
21 type: str
22 resource_group:
23 description:
24 - Name of a resource group where the topic exists or will be created.
25 required: true
26 type: str
27 location:
28 description:
29 - Valid azure location. Defaults to location of the resource group.
30 type: str
31 input_schema:
32 description:
33 - Schema in which incoming events will be published to this topic/domain.
34 If you specify CustomEventSchema as the value for this parameter, you must
35 also provide values for at least one of input_mapping_default_values /
36 input_mapping_fields.
37 type: str
38 choices:
39 - CloudEventSchemaV1_0
40 - CustomEventSchema
41 - EventGridSchema
42 default: EventGridSchema
43 input_mapping_default_values:
44 description:
45 - When input_schema is specified as CustomEventSchema, this parameter can be
46 used to specify input mappings based on default values. You can use this
47 parameter when your custom schema does not include a field that corresponds
48 to one of the three fields supported by this parameter.
49 type: list
50 elements: dict
51 suboptions:
52 mapping_key:
53 description:
54 - Parameter name
55 type: str
56 choices:
57 - subject
58 - eventtype
59 - dataversion
60 mapping_value:
61 description:
62 - Default value to use for Parameter when not in publish event.
63 type: str
64 input_mapping_fields:
65 description:
66 - When input_schema is specified as CustomEventSchema, this parameter is used
67 to specify input mappings based on field names.
68 type: list
69 elements: dict
70 suboptions:
71 mapping_key:
72 description:
73 - Parameter name
74 type: str
75 choices:
76 - id
77 - topic
78 - eventtime
79 - subject
80 - eventtype
81 - dataversion
82 mapping_value:
83 description:
84 - Corresponding value should specify the name of the field in the custom
85 input schema. If a mapping for either 'id' or 'eventtime' is not
86 provided, Event Grid will auto-generate a default value for these two
87 fields.
88 type: str
89 inbound_ip_rules:
90 description:
91 - List of inbound IP rules
92 required: false
93 type: list
94 default: []
95 elements: dict
96 suboptions:
97 ipmask:
98 description:
99 - IP Address in CIDR notation e.g., 10.0.0.0/8
100 type: str
101 action:
102 description:
103 - Action to perform based ont the match or no match of the IpMask.
104 type: str
105 choices:
106 - Allow
107 - Deny
108 public_network_access:
109 description:
110 - This determines if traffic is allowed over public network.
111 choices:
112 - enabled
113 - disabled
114 type: str
115 default: enabled
116 identity:
117 description:
118 - Identity for the Server.
119 type: dict
120 suboptions:
121 type:
122 description:
123 - Type of the managed identity
124 choices:
125 - UserAssigned
126 - SystemAssigned
127 - SystemAssigned UserAssigned
128 - None
129 default: SystemAssigned
130 type: str
131 user_assigned_identities:
132 description:
133 - User Assigned Managed Identity
134 type: list
135 elements: str
136 kind:
137 description:
138 - The kind of topic resource.
139 default: Azure
140 type: str
141 choices:
142 - Azure
143 - AzureArc
144 extended_location_name:
145 description:
146 - The extended location name.
147 - Required if I(kind=AzureArc).
148 type: str
149 extended_location_type:
150 description:
151 - The extended location type.
152 - Required if I(kind=AzureArc).
153 type: str
154 choices:
155 - customlocation
156 state:
157 description:
158 - State of the Eventgrid Topic. Use C(present) to create or update and C(absent) to delete.
159 default: present
160 type: str
161 choices:
162 - absent
163 - present
164 regenerate_keys:
165 description:
166 - if C(present) and topic exsists (ie update action) this will force
167 the listed key to be regeneratd. This cannot be idempotent. Everytime
168 this is called it will regenerate the key(s).
169 type: list
170 elements: str
171 choices:
172 - key1
173 - key2
174
175 extends_documentation_fragment:
176 - azure.azcollection.azure
177 - azure.azcollection.azure_tags
178
179 author:
180 - Bill Peck (@p3ck)
181 '''
182
183 EXAMPLES = '''
184 - name: Create a new Topic
185 azure.azcollection.azure_rm_eventgrid_topic:
186 resource_group: rg1
187 name: topic1
188 location: westus2
189
190 - name: Create a new Topic with custom input mappings
191 azure.azcollection.azure_rm_eventgrid_topic:
192 resource_group: rg1
193 name: topic1
194 location: westus2
195 input_schema: CustomEventSchema
196 input_mapping_fields:
197 - mapping_key: topic
198 mapping_value: myTopicField
199 - mapping_key: eventtype
200 mapping_value: myEventTypeField
201 input_mapping_default_values:
202 - mapping_key: subject
203 mapping_value: DefaultSubject
204 - mapping_key: dataversion
205 mapping_value: 1.0
206
207 - name: Create a new Topic that accepts events published in CloudEvents V1.0 schema
208 azure.azcollection.azure_rm_eventgrid_topic:
209 resource_group: rg1
210 name: topic1
211 location: westus2
212 input_schema: CloudEventSchemaV1_0
213
214 - name: Create a new Topic which allows specific inbound ip rules with Basic Sku and system assigned
215 azure.azcollection.azure_rm_eventgrid_topic:
216 resource_group: rg1
217 name: topic1
218 location: westus2
219 public_network_access: enabled
220 inbound_ip_rules:
221 - ipmask: 10.0.0.0/8
222 action: Allow
223 - ipmask: 10.2.0.0/8
224 action: Allow
225 identity:
226 type: SystemAssigned
227
228 - name: Create a new topic in AzureArc targeting a custom location
229 azure.azcollection.azure_rm_eventgrid_topic:
230 resource_group: rg1
231 name: topic1
232 location: eastus2euap
233 kind: azurearc
234 extended_location_name: /subscriptions/<subid>/resourcegroups/<rgname>/providers/microsoft.extendedlocation/customlocations/<cust-loc-name>
235 extended_location_type: customlocation
236 input_schema: CloudEventSchemaV1_0
237
238 - name: Delete the topic
239 azure.azcollection.azure_rm_eventgrid_topic:
240 resource_group: rg1
241 name: topic1
242 state: absent
243 '''
244
245 RETURN = '''
246 changed:
247 description:
248 - Whether the resource is changed.
249 returned: always
250 type: bool
251 sample: true
252 eventgrid_topic:
253 description:
254 - Eventgrid Topic.
255 returned: always
256 type: complex
257 contains:
258 data_residency_boundary:
259 description:
260 - Residncy boundary
261 returned: always
262 type: str
263 sample: WithinGeopair
264 disable_local_auth:
265 description:
266 - Whether local auth is disabled
267 returned: always
268 type: bool
269 sample: false
270 endpoint:
271 description:
272 - Rest API endpoint to use to post events
273 returned: always
274 type: str
275 sample: https://myTopic-20070.westus3-1.eventgrid.azure.net/api/events
276 id:
277 description:
278 - Resource ID.
279 returned: always
280 type: str
281 sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.EventGrid/topics/myTopic
282 inbound_ip_rules:
283 description:
284 - Rules for network access
285 type: complex
286 returned: when-enabled
287 contains:
288 action:
289 description:
290 - What action will be taken, Allow or Disallow
291 returned: always
292 type: str
293 sample: Allow
294 ip_mask:
295 description:
296 - CIDR notation of the network to act on.
297 returned: always
298 type: str
299 sample: 10.0.0.0/8
300 input_schema:
301 description:
302 - The input schema assigned to this Topic
303 returned: always
304 type: str
305 sample: EventGridSchema
306 location:
307 description:
308 - Resource location.
309 returned: always
310 type: str
311 sample: westus3
312 metric_resource_id:
313 description:
314 - Metric Resource ID.
315 returned: always
316 type: str
317 sample: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
318 minimum_tls_version_allowed:
319 description:
320 - The minimum TLS version allowed
321 returned: always
322 type: str
323 sample: 1.0
324 name:
325 description:
326 - Resource name.
327 returned: always
328 type: str
329 sample: myTopic
330 provisioning_state:
331 description:
332 - The provisioning state.
333 returned: always
334 type: str
335 sample: Succeeded
336 public_network_access:
337 description:
338 - Indicates if boot diagnostics are enabled.
339 returned: always
340 type: str
341 sample: Enabled
342 type:
343 description:
344 - Type of Eventgrid
345 type: str
346 returned: always
347 sample: Microsoft.EventGrid/topics
348 input_schema_mapping:
349 description:
350 - Custom input schema mapping
351 type: str
352 returned: when-enabled
353 sample: |
354 "data_version": {
355 "default_value": "1.0"
356 },
357 "event_time": {},
358 "event_type": {
359 "source_field": "myEventTypeField"
360 },
361 "id": {},
362 "input_schema_mapping_type": "Json",
363 "subject": {
364 "default_value": "DefaultSubject"
365 },
366 "topic": {
367 "source_field": "myTopicField"
368 }
369 '''
370
371
372 try:
373 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
374 from azure.mgmt.eventgrid import EventGridManagementClient
375 from azure.core.polling import LROPoller
376 from azure.core.exceptions import ResourceNotFoundError
377 except ImportError:
378 # This is handled in azure_rm_common
379 pass
380
381 managed_identity_spec = dict(
382 type=dict(
383 type='str',
384 default='SystemAssigned',
385 choices=['SystemAssigned',
386 'UserAssigned',
387 'SystemAssigned UserAssigned',
388 'None'],
389 ),
390 user_assigned_identities=dict(
391 type='list',
392 elements='str'
393 ),
394 )
395
396 input_mapping_default_values_spec = dict(
397 mapping_key=dict(
398 type='str',
399 choices=['subject',
400 'eventtype',
401 'dataversion'],
402 ),
403 mapping_value=dict(
404 type='str'
405 ),
406 )
407
408 input_mapping_fields_spec = dict(
409 mapping_key=dict(
410 type='str',
411 choices=['id',
412 'topic',
413 'eventtime',
414 'subject',
415 'eventtype',
416 'dataversion'],
417 ),
418 mapping_value=dict(
419 type='str'
420 ),
421 )
422
423 inbound_ip_rules_spec = dict(
424 ipmask=dict(
425 type='str'
426 ),
427 action=dict(
428 type='str',
429 choices=['Allow',
430 'Deny']
431 )
432 )
433
434
435 class AzureRMEventgridTopic(AzureRMModuleBaseExt):
436
437 @property
438 def client(self):
439 self.log('Getting client')
440 if not self._client:
441 self._client = self.get_mgmt_svc_client(EventGridManagementClient,
442 base_url=self._cloud_environment.endpoints.resource_manager)
443 return self._client
444
445 @property
446 def models(self):
447 self.log('Getting models')
448 return self.client.topics.models
449
450 def __init__(self):
451
452 self.module_arg_spec = dict(
453 name=dict(
454 type='str',
455 required=True
456 ),
457 resource_group=dict(
458 type='str',
459 required=True
460 ),
461 location=dict(
462 type='str'
463 ),
464 input_schema=dict(
465 type='str',
466 default='EventGridSchema',
467 choices=['CloudEventSchemaV1_0', 'CustomEventSchema', 'EventGridSchema']
468 ),
469 input_mapping_default_values=dict(
470 type='list',
471 elements='dict',
472 options=input_mapping_default_values_spec,
473 required_together=[('mapping_key', 'mapping_value')],
474 ),
475 input_mapping_fields=dict(
476 type='list',
477 elements='dict',
478 options=input_mapping_fields_spec,
479 required_together=[('mapping_key', 'mapping_value')],
480 ),
481 inbound_ip_rules=dict(
482 type='list',
483 default=[],
484 elements='dict',
485 options=inbound_ip_rules_spec,
486 required_together=[('ipmask', 'action')],
487 ),
488 public_network_access=dict(
489 type='str',
490 default='enabled',
491 choices=['enabled', 'disabled']
492 ),
493 identity=dict(
494 type='dict',
495 options=managed_identity_spec
496 ),
497 kind=dict(
498 type='str',
499 default='Azure',
500 choices=['Azure', 'AzureArc']
501 ),
502 extended_location_name=dict(
503 type='str'
504 ),
505 extended_location_type=dict(
506 type='str',
507 choices=['customlocation']
508 ),
509 state=dict(
510 type='str',
511 default='present',
512 choices=['present', 'absent']
513 ),
514 regenerate_keys=dict(
515 type='list',
516 elements='str',
517 choices=['key1', 'key2']
518 ),
519 )
520
521 self._client = None
522
523 self.name = None
524 self.location = None
525 self.input_schema = None
526 self.input_mapping_default_values = None
527 self.input_mapping_fields = None
528 self.inbound_ip_rules = None
529 self.public_network_access = None
530 self.identity = None
531 self.kind = None
532 self.extended_location_name = None
533 self.extended_location_type = None
534 self.state = None
535 self.regenerate_keys = None
536
537 self.results = dict(
538 changed=False,
539 eventgrid_topic=dict()
540 )
541
542 required_together = [['extended_location_name', 'extended_location_type']]
543 required_if = [
544 ("kind", "AzureArc", ["extended_location_name"]),
545 ]
546
547 super(AzureRMEventgridTopic, self).__init__(self.module_arg_spec,
548 supports_tags=True,
549 supports_check_mode=True,
550 required_together=required_together,
551 required_if=required_if,
552 )
553
554 def exec_module(self, **kwargs):
555
556 for key in list(self.module_arg_spec.keys()) + ['tags']:
557 setattr(self, key, kwargs[key])
558
559 changed = False
560
561 identity_info = self._get_identity_info_only_if_not_none(self.identity, self.kind)
562 input_schema_mapping = self._get_input_schema_and_mapping(self.input_mapping_fields,
563 self.input_mapping_default_values)
564 inbound_ip_rules = self._get_inbound_ip_rules(self.inbound_ip_rules)
565 extended_location = self._get_extended_location(self.kind,
566 self.extended_location_name,
567 self.extended_location_type)
568
569 if self.state == 'present':
570 response = self.get_eventgrid_topic(self.resource_group,
571 self.name)
572 if response:
573 topic_update_parameters = self.models.TopicUpdateParameters(tags=self.tags,
574 public_network_access=self.public_network_access,
575 inbound_ip_rules=inbound_ip_rules,
576 identity=identity_info)
577
578 self.results['compare'] = []
579 changed = not self.default_compare({},
580 self.format_eventgrid_topic(topic_update_parameters),
581 response,
582 '',
583 self.results)
584 if changed and not self.check_mode:
585 topic_info = self.models.Topic(
586 location=response.get('location', self.location),
587 tags=self.tags,
588 input_schema=response.get('input_schema', self.input_schema),
589 input_schema_mapping=input_schema_mapping,
590 public_network_access=self.public_network_access,
591 inbound_ip_rules=inbound_ip_rules,
592 identity=identity_info,
593 disable_local_auth=response.get('disable_local_auth', False),
594 data_residency_boundary=response.get('data_residency_boundary'),
595 minimum_tls_version_allowed=response.get('minimum_tls_version_allowed'),
596 kind=self.kind,
597 extended_location=extended_location)
598 response = self.begin_create_or_update_eventgrid_topic(self.resource_group,
599 self.name,
600 topic_info)
601 if self.regenerate_keys and not self.check_mode:
602 changed = True
603 for key_name in self.regenerate_keys:
604 key_response = self.topic_regenerate_key(self.resource_group,
605 self.name,
606 key_name)
607
608 else:
609 changed = True
610 topic_info = self.models.Topic(
611 location=self.location,
612 tags=self.tags,
613 input_schema=self.input_schema,
614 input_schema_mapping=input_schema_mapping,
615 public_network_access=self.public_network_access,
616 inbound_ip_rules=inbound_ip_rules,
617 identity=identity_info,
618 kind=self.kind,
619 extended_location=extended_location)
620
621 if not self.check_mode:
622 response = self.begin_create_or_update_eventgrid_topic(self.resource_group,
623 self.name,
624 topic_info)
625 else:
626 response = self.get_eventgrid_topic(self.resource_group,
627 self.name)
628 if response:
629 changed = True
630 if not self.check_mode:
631 response = self.delete_eventgrid_topic(self.resource_group,
632 self.name)
633
634 self.results['changed'] = changed
635 self.results['eventgrid_topic'] = response
636
637 return self.results
638
639 def begin_create_or_update_eventgrid_topic(self, resource_group, topic_name, topic_info):
640 self.log('Creates or updates the Eventgrid Topic.')
641
642 try:
643 response = self.client.topics.begin_create_or_update(resource_group, topic_name, topic_info)
644 if isinstance(response, LROPoller):
645 response = self.get_poller_result(response)
646 except Exception as exc:
647 self.fail('Creates or updates the Eventgrid Topic got Exception as as {0}'.format(exc.message or str(exc)))
648 return self.format_eventgrid_topic(response)
649
650 def begin_update_eventgrid_topic(self, resource_group, topic_name, topic_update_parameters):
651 self.log('Selectively updates the Eventgrid Topic.')
652
653 try:
654 response = self.client.topics.begin_update(resource_group_name=resource_group,
655 topic_name=topic_name,
656 topic_update_parameters=topic_update_parameters)
657 if isinstance(response, LROPoller):
658 response = self.get_poller_result(response)
659 except Exception as exc:
660 self.fail('Selectively updates the Eventgrid Topic got Excption as {0}'.format(exc.message or str(exc)))
661
662 return self.format_eventgrid_topic(response)
663
664 def delete_eventgrid_topic(self, resource_group, topic_name):
665 self.log('Deletes the entire Eventgrid Topic.')
666 try:
667 self.client.topics.begin_delete(resource_group, topic_name)
668 except Exception as exc:
669 self.fail('Delete the entire set of tag got Excetion as {0}'.format(exc.message or str(exc)))
670
671 def get_eventgrid_topic(self, resource_group, topic_name):
672 self.log('Get properties for {0}'.format(topic_name))
673 try:
674 response = self.client.topics.get(resource_group, topic_name)
675 if response is not None:
676 return self.format_eventgrid_topic(response)
677 except ResourceNotFoundError:
678 self.log('Did not find the eventgrid_topic.')
679 return False
680 except Exception as exc:
681 self.fail('Error when get eventgrid_topic got Excetion as {0}'.format(exc.message or str(exc)))
682
683 def format_eventgrid_topic(self, topic_data):
684 results = topic_data and topic_data.as_dict() or {}
685 return results
686
687 def _get_identity_info_only_if_not_none(self, identity=None, kind=None):
688 identity_info = None
689 if identity:
690 # If UserAssigned in module args and ids specified
691 if 'UserAssigned' in identity.get('type') and len(identity.get('user_assigned_identities', [])) != 0:
692 user_assigned_identities_dict = {uami: self.models.UserIdentityProperties() for uami in identity.get('user_assigned_identities')}
693 # Append identities to the model
694 identity_info = self.models.IdentityInfo(
695 type=identity.get('type'),
696 user_assigned_identities=user_assigned_identities_dict
697 )
698 # If UserAssigned in module args, but ids are not specified
699 elif 'UserAssigned' in identity.get('type') and len(identity.get('user_assigned_identities', [])) == 0:
700 self.fail("UserAssigned specified but no User Identity IDs provided")
701 # In any other case ('SystemAssigned' or 'None') apply the configuration to the model
702 else:
703 identity_info = self.models.IdentityInfo(
704 type=identity.get('type')
705 )
706 else:
707 if kind is None or kind == 'Azure':
708 indentity_info = self.models.IdentityInfo(type="None")
709
710 return identity_info
711
712 def _get_input_schema_and_mapping(self,
713 input_mapping_fields=None,
714 input_mapping_default_values=None):
715
716 input_schema_mapping = None
717
718 if input_mapping_fields is not None or input_mapping_default_values is not None:
719 input_schema_mapping = self.models.JsonInputSchemaMapping()
720
721 input_schema_mapping.id = self.models.JsonField()
722 input_schema_mapping.topic = self.models.JsonField()
723 input_schema_mapping.event_time = self.models.JsonField()
724 input_schema_mapping.subject = self.models.JsonFieldWithDefault()
725 input_schema_mapping.event_type = self.models.JsonFieldWithDefault()
726 input_schema_mapping.data_version = self.models.JsonFieldWithDefault()
727
728 if input_mapping_fields is not None:
729 for input_mapping_field in input_mapping_fields:
730 target = input_mapping_field.get('mapping_key')
731 source = input_mapping_field.get('mapping_value')
732 if target == 'id':
733 input_schema_mapping.id.source_field = source
734 elif target == 'eventtime':
735 input_schema_mapping.event_time.source_field = source
736 elif target == 'topic':
737 input_schema_mapping.topic.source_field = source
738 elif target == 'subject':
739 input_schema_mapping.subject.source_field = source
740 elif target == 'dataversion':
741 input_schema_mapping.data_version.source_field = source
742 elif target == 'eventtype':
743 input_schema_mapping.event_type.source_field = source
744
745 if input_mapping_default_values is not None:
746 for input_mapping_default_value in input_mapping_default_values:
747 target = input_mapping_default_value.get('mapping_key')
748 source = input_mapping_default_value.get('mapping_value')
749 if target == 'subject':
750 input_schema_mapping.subject.default_value = source
751 elif target == 'dataversion':
752 input_schema_mapping.data_version.default_value = source
753 elif target == 'eventtype':
754 input_schema_mapping.event_type.default_value = source
755
756 return input_schema_mapping
757
758 def _get_inbound_ip_rules(self, inbound_ip_rules):
759 inbound_ip_rules_mapping = []
760
761 for inbound_ip_rule in inbound_ip_rules:
762 ipmask = inbound_ip_rule.get('ipmask')
763 action = inbound_ip_rule.get('action')
764 inbound_ip_rules_mapping.append(self.models.InboundIpRule(ip_mask=ipmask, action=action))
765
766 return inbound_ip_rules_mapping
767
768 def _get_extended_location(self, kind_name=None, extended_location_name=None,
769 extended_location_type=None):
770 result = None
771
772 if kind_name == 'AzureArc':
773 result = self.models.ExtendedLocation(name=extended_location_name,
774 type=extended_location_type)
775
776 return result
777
778 def topic_regenerate_key(self,
779 resource_group,
780 topic_name,
781 key_name):
782 regenerate_key_request = self.models.TopicRegenerateKeyRequest(key_name=key_name)
783
784 return self.client.topics.begin_regenerate_key(
785 resource_group_name=resource_group,
786 topic_name=topic_name,
787 regenerate_key_request=regenerate_key_request
788 )
789
790
791 def main():
792 AzureRMEventgridTopic()
793
794
795 if __name__ == '__main__':
796 main()