Debian Codegraph @

ansible_collections/community/aws/plugins/module_utils/sns.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: Contributors to the Ansible project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 import copy
7 import re
8
9 try:
10 import botocore
11 except ImportError:
12 pass # handled by AnsibleAWSModule
13
14 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
15
16 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
17 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
18 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
19 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
20 from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags
21
22
23 @AWSRetry.jittered_backoff()
24 def _list_topics_with_backoff(client):
25 paginator = client.get_paginator("list_topics")
26 return paginator.paginate().build_full_result()["Topics"]
27
28
29 @AWSRetry.jittered_backoff(catch_extra_error_codes=["NotFound"])
30 def _list_topic_subscriptions_with_backoff(client, topic_arn):
31 paginator = client.get_paginator("list_subscriptions_by_topic")
32 return paginator.paginate(TopicArn=topic_arn).build_full_result()["Subscriptions"]
33
34
35 @AWSRetry.jittered_backoff(catch_extra_error_codes=["NotFound"])
36 def _list_subscriptions_with_backoff(client):
37 paginator = client.get_paginator("list_subscriptions")
38 return paginator.paginate().build_full_result()["Subscriptions"]
39
40
41 def list_topic_subscriptions(client, module, topic_arn):
42 try:
43 return _list_topic_subscriptions_with_backoff(client, topic_arn)
44 except is_boto3_error_code("AuthorizationError"):
45 try:
46 # potentially AuthorizationError when listing subscriptions for third party topic
47 return [sub for sub in _list_subscriptions_with_backoff(client) if sub["TopicArn"] == topic_arn]
48 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
49 module.fail_json_aws(e, msg=f"Couldn't get subscriptions list for topic {topic_arn}")
50 except (
51 botocore.exceptions.ClientError,
52 botocore.exceptions.BotoCoreError,
53 ) as e: # pylint: disable=duplicate-except
54 module.fail_json_aws(e, msg=f"Couldn't get subscriptions list for topic {topic_arn}")
55
56
57 def list_topics(client, module):
58 try:
59 topics = _list_topics_with_backoff(client)
60 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
61 module.fail_json_aws(e, msg="Couldn't get topic list")
62 return [t["TopicArn"] for t in topics]
63
64
65 def topic_arn_lookup(client, module, name):
66 # topic names cannot have colons, so this captures the full topic name
67 all_topics = list_topics(client, module)
68 lookup_topic = f":{name}"
69 for topic in all_topics:
70 if topic.endswith(lookup_topic):
71 return topic
72
73
74 def compare_delivery_policies(policy_a, policy_b):
75 _policy_a = copy.deepcopy(policy_a)
76 _policy_b = copy.deepcopy(policy_b)
77 # AWS automatically injects disableSubscriptionOverrides if you set an
78 # http policy
79 if "http" in policy_a:
80 if "disableSubscriptionOverrides" not in policy_a["http"]:
81 _policy_a["http"]["disableSubscriptionOverrides"] = False
82 if "http" in policy_b:
83 if "disableSubscriptionOverrides" not in policy_b["http"]:
84 _policy_b["http"]["disableSubscriptionOverrides"] = False
85 comparison = _policy_a != _policy_b
86 return comparison
87
88
89 def canonicalize_endpoint(protocol, endpoint):
90 # AWS SNS expects phone numbers in
91 # and canonicalizes to E.164 format
92 # See <https://docs.aws.amazon.com/sns/latest/dg/sms_publish-to-phone.html>
93 if protocol == "sms":
94 return re.sub("[^0-9+]*", "", endpoint)
95 return endpoint
96
97
98 def get_tags(client, module, topic_arn):
99 try:
100 return boto3_tag_list_to_ansible_dict(client.list_tags_for_resource(ResourceArn=topic_arn)["Tags"])
101 except is_boto3_error_code("AuthorizationError"):
102 module.warn("Permission denied accessing tags")
103 return {}
104 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
105 module.fail_json_aws(e, msg="Couldn't obtain topic tags")
106
107
108 def get_info(connection, module, topic_arn):
109 name = module.params.get("name")
110 topic_type = module.params.get("topic_type")
111 state = module.params.get("state")
112 subscriptions = module.params.get("subscriptions")
113 purge_subscriptions = module.params.get("purge_subscriptions")
114 content_based_deduplication = module.params.get("content_based_deduplication")
115 subscriptions_existing = module.params.get("subscriptions_existing", [])
116 subscriptions_deleted = module.params.get("subscriptions_deleted", [])
117 subscriptions_added = module.params.get("subscriptions_added", [])
118 subscriptions_added = module.params.get("subscriptions_added", [])
119 topic_created = module.params.get("topic_created", False)
120 topic_deleted = module.params.get("topic_deleted", False)
121 attributes_set = module.params.get("attributes_set", [])
122 check_mode = module.check_mode
123
124 info = {
125 "name": name,
126 "topic_type": topic_type,
127 "state": state,
128 "subscriptions_new": subscriptions,
129 "subscriptions_existing": subscriptions_existing,
130 "subscriptions_deleted": subscriptions_deleted,
131 "subscriptions_added": subscriptions_added,
132 "subscriptions_purge": purge_subscriptions,
133 "content_based_deduplication": content_based_deduplication,
134 "check_mode": check_mode,
135 "topic_created": topic_created,
136 "topic_deleted": topic_deleted,
137 "attributes_set": attributes_set,
138 }
139 if state != "absent":
140 if topic_arn in list_topics(connection, module):
141 info.update(camel_dict_to_snake_dict(connection.get_topic_attributes(TopicArn=topic_arn)["Attributes"]))
142 info["delivery_policy"] = info.pop("effective_delivery_policy")
143 info["subscriptions"] = [
144 camel_dict_to_snake_dict(sub) for sub in list_topic_subscriptions(connection, module, topic_arn)
145 ]
146 info["tags"] = get_tags(connection, module, topic_arn)
147 return info
148
149
150 def update_tags(client, module, topic_arn):
151 if module.params.get("tags") is None:
152 return False
153
154 existing_tags = get_tags(client, module, topic_arn)
155 to_update, to_delete = compare_aws_tags(existing_tags, module.params["tags"], module.params["purge_tags"])
156
157 if not bool(to_delete or to_update):
158 return False
159
160 if module.check_mode:
161 return True
162
163 if to_update:
164 try:
165 client.tag_resource(ResourceArn=topic_arn, Tags=ansible_dict_to_boto3_tag_list(to_update))
166 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
167 module.fail_json_aws(e, msg="Couldn't add tags to topic")
168 if to_delete:
169 try:
170 client.untag_resource(ResourceArn=topic_arn, TagKeys=to_delete)
171 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
172 module.fail_json_aws(e, msg="Couldn't remove tags from topic")
173
174 return True