Debian Codegraph @

ansible_collections/community/aws/plugins/modules/ses_identity.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2017 Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 DOCUMENTATION = r"""
8 ---
9 module: ses_identity
10 version_added: 1.0.0
11 short_description: Manages SES email and domain identity
12 description:
13 - This module allows the user to manage verified email and domain identity for SES.
14 - This covers verifying and removing identities as well as setting up complaint, bounce
15 and delivery notification settings.
16 - Prior to release 5.0.0 this module was called C(community.aws.aws_ses_identity).
17 The usage did not change.
18 author:
19 - Ed Costello (@orthanc)
20 options:
21 identity:
22 description:
23 - This is the email address or domain to verify / delete.
24 - If this contains an '@' then it will be considered an email. Otherwise it will be considered a domain.
25 required: true
26 type: str
27 state:
28 description: Whether to create(or update) or delete the identity.
29 default: present
30 choices: [ 'present', 'absent' ]
31 type: str
32 bounce_notifications:
33 description:
34 - Setup the SNS topic used to report bounce notifications.
35 - If omitted, bounce notifications will not be delivered to a SNS topic.
36 - If bounce notifications are not delivered to a SNS topic, I(feedback_forwarding) must be enabled.
37 suboptions:
38 topic:
39 description:
40 - The ARN of the topic to send notifications to.
41 - If omitted, notifications will not be delivered to a SNS topic.
42 include_headers:
43 description:
44 - Whether or not to include headers when delivering to the SNS topic.
45 - If I(topic) is not specified this will have no impact, but the SES setting is updated even if there is no topic.
46 type: bool
47 default: No
48 type: dict
49 complaint_notifications:
50 description:
51 - Setup the SNS topic used to report complaint notifications.
52 - If omitted, complaint notifications will not be delivered to a SNS topic.
53 - If complaint notifications are not delivered to a SNS topic, I(feedback_forwarding) must be enabled.
54 suboptions:
55 topic:
56 description:
57 - The ARN of the topic to send notifications to.
58 - If omitted, notifications will not be delivered to a SNS topic.
59 include_headers:
60 description:
61 - Whether or not to include headers when delivering to the SNS topic.
62 - If I(topic) is not specified this will have no impact, but the SES setting is updated even if there is no topic.
63 type: bool
64 default: No
65 type: dict
66 delivery_notifications:
67 description:
68 - Setup the SNS topic used to report delivery notifications.
69 - If omitted, delivery notifications will not be delivered to a SNS topic.
70 suboptions:
71 topic:
72 description:
73 - The ARN of the topic to send notifications to.
74 - If omitted, notifications will not be delivered to a SNS topic.
75 include_headers:
76 description:
77 - Whether or not to include headers when delivering to the SNS topic.
78 - If I(topic) is not specified this will have no impact, but the SES setting is updated even if there is no topic.
79 type: bool
80 default: No
81 type: dict
82 feedback_forwarding:
83 description:
84 - Whether or not to enable feedback forwarding.
85 - This can only be false if both I(bounce_notifications) and I(complaint_notifications) specify SNS topics.
86 type: 'bool'
87 default: true
88 extends_documentation_fragment:
89 - amazon.aws.common.modules
90 - amazon.aws.region.modules
91 - amazon.aws.boto3
92 """
93
94 EXAMPLES = r"""
95 # Note: These examples do not set authentication details, see the AWS Guide for details.
96
97 - name: Ensure [email protected] email identity exists
98 community.aws.ses_identity:
99 identity: [email protected]
100 state: present
101
102 - name: Delete [email protected] email identity
103 community.aws.ses_identity:
104 email: [email protected]
105 state: absent
106
107 - name: Ensure example.com domain identity exists
108 community.aws.ses_identity:
109 identity: example.com
110 state: present
111
112 # Create an SNS topic and send bounce and complaint notifications to it
113 # instead of emailing the identity owner
114 - name: Ensure complaints-topic exists
115 community.aws.sns_topic:
116 name: "complaints-topic"
117 state: present
118 purge_subscriptions: false
119 register: topic_info
120
121 - name: Deliver feedback to topic instead of owner email
122 community.aws.ses_identity:
123 identity: [email protected]
124 state: present
125 complaint_notifications:
126 topic: "{{ topic_info.sns_arn }}"
127 include_headers: true
128 bounce_notifications:
129 topic: "{{ topic_info.sns_arn }}"
130 include_headers: false
131 feedback_forwarding: false
132
133 # Create an SNS topic for delivery notifications and leave complaints
134 # Being forwarded to the identity owner email
135 - name: Ensure delivery-notifications-topic exists
136 community.aws.sns_topic:
137 name: "delivery-notifications-topic"
138 state: present
139 purge_subscriptions: false
140 register: topic_info
141
142 - name: Delivery notifications to topic
143 community.aws.ses_identity:
144 identity: [email protected]
145 state: present
146 delivery_notifications:
147 topic: "{{ topic_info.sns_arn }}"
148 """
149
150 RETURN = r"""
151 identity:
152 description: The identity being modified.
153 returned: success
154 type: str
155 sample: [email protected]
156 identity_arn:
157 description: The arn of the identity being modified.
158 returned: success
159 type: str
160 sample: arn:aws:ses:us-east-1:12345678:identity/[email protected]
161 verification_attributes:
162 description: The verification information for the identity.
163 returned: success
164 type: complex
165 sample: {
166 "verification_status": "Pending",
167 "verification_token": "...."
168 }
169 contains:
170 verification_status:
171 description: The verification status of the identity.
172 type: str
173 sample: "Pending"
174 verification_token:
175 description: The verification token for a domain identity.
176 type: str
177 notification_attributes:
178 description: The notification setup for the identity.
179 returned: success
180 type: complex
181 sample: {
182 "bounce_topic": "arn:aws:sns:....",
183 "complaint_topic": "arn:aws:sns:....",
184 "delivery_topic": "arn:aws:sns:....",
185 "forwarding_enabled": false,
186 "headers_in_bounce_notifications_enabled": true,
187 "headers_in_complaint_notifications_enabled": true,
188 "headers_in_delivery_notifications_enabled": true
189 }
190 contains:
191 bounce_topic:
192 description:
193 - The ARN of the topic bounce notifications are delivered to.
194 - Omitted if bounce notifications are not delivered to a topic.
195 type: str
196 complaint_topic:
197 description:
198 - The ARN of the topic complaint notifications are delivered to.
199 - Omitted if complaint notifications are not delivered to a topic.
200 type: str
201 delivery_topic:
202 description:
203 - The ARN of the topic delivery notifications are delivered to.
204 - Omitted if delivery notifications are not delivered to a topic.
205 type: str
206 forwarding_enabled:
207 description: Whether or not feedback forwarding is enabled.
208 type: bool
209 headers_in_bounce_notifications_enabled:
210 description: Whether or not headers are included in messages delivered to the bounce topic.
211 type: bool
212 headers_in_complaint_notifications_enabled:
213 description: Whether or not headers are included in messages delivered to the complaint topic.
214 type: bool
215 headers_in_delivery_notifications_enabled:
216 description: Whether or not headers are included in messages delivered to the delivery topic.
217 type: bool
218 """
219
220 import time
221
222 try:
223 from botocore.exceptions import BotoCoreError
224 from botocore.exceptions import ClientError
225 except ImportError:
226 pass # caught by AnsibleAWSModule
227
228 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
229
230 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
231
232 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
233
234
235 def get_verification_attributes(connection, module, identity, retries=0, retryDelay=10):
236 # Unpredictably get_identity_verification_attributes doesn't include the identity even when we've
237 # just registered it. Suspect this is an eventual consistency issue on AWS side.
238 # Don't want this complexity exposed users of the module as they'd have to retry to ensure
239 # a consistent return from the module.
240 # To avoid this we have an internal retry that we use only after registering the identity.
241 for attempt in range(0, retries + 1):
242 try:
243 response = connection.get_identity_verification_attributes(Identities=[identity], aws_retry=True)
244 except (BotoCoreError, ClientError) as e:
245 module.fail_json_aws(e, msg=f"Failed to retrieve identity verification attributes for {identity}")
246 identity_verification = response["VerificationAttributes"]
247 if identity in identity_verification:
248 break
249 time.sleep(retryDelay)
250 if identity not in identity_verification:
251 return None
252 return identity_verification[identity]
253
254
255 def get_identity_notifications(connection, module, identity, retries=0, retryDelay=10):
256 # Unpredictably get_identity_notifications doesn't include the notifications when we've
257 # just registered the identity.
258 # Don't want this complexity exposed users of the module as they'd have to retry to ensure
259 # a consistent return from the module.
260 # To avoid this we have an internal retry that we use only when getting the current notification
261 # status for return.
262 for attempt in range(0, retries + 1):
263 try:
264 response = connection.get_identity_notification_attributes(Identities=[identity], aws_retry=True)
265 except (BotoCoreError, ClientError) as e:
266 module.fail_json_aws(e, msg=f"Failed to retrieve identity notification attributes for {identity}")
267 notification_attributes = response["NotificationAttributes"]
268
269 # No clear AWS docs on when this happens, but it appears sometimes identities are not included in
270 # in the notification attributes when the identity is first registered. Suspect that this is caused by
271 # eventual consistency within the AWS services. It's been observed in builds so we need to handle it.
272 #
273 # When this occurs, just return None and we'll assume no identity notification settings have been changed
274 # from the default which is reasonable if this is just eventual consistency on creation.
275 # See: https://github.com/ansible/ansible/issues/36065
276 if identity in notification_attributes:
277 break
278
279 # Paranoia check for coding errors, we only requested one identity, so if we get a different one
280 # something has gone very wrong.
281 if len(notification_attributes) != 0:
282 module.fail_json(
283 msg="Unexpected identity found in notification attributes, expected {0} but got {1!r}.".format(
284 identity,
285 notification_attributes.keys(),
286 )
287 )
288
289 time.sleep(retryDelay)
290 if identity not in notification_attributes:
291 return None
292 return notification_attributes[identity]
293
294
295 def desired_topic(module, notification_type):
296 arg_dict = module.params.get(notification_type.lower() + "_notifications")
297 if arg_dict:
298 return arg_dict.get("topic", None)
299 else:
300 return None
301
302
303 def update_notification_topic(connection, module, identity, identity_notifications, notification_type):
304 # Not passing the parameter should not cause any changes.
305 if module.params.get(f"{notification_type.lower()}_notifications") is None:
306 return False
307
308 topic_key = notification_type + "Topic"
309 if identity_notifications is None:
310 # If there is no configuration for notifications cannot be being sent to topics
311 # hence assume None as the current state.
312 current_topic = None
313 elif topic_key in identity_notifications:
314 current_topic = identity_notifications[topic_key]
315 else:
316 # If there is information on the notifications setup but no information on the
317 # particular notification topic it's pretty safe to assume there's no topic for
318 # this notification. AWS API docs suggest this information will always be
319 # included but best to be defensive
320 current_topic = None
321
322 required_topic = desired_topic(module, notification_type)
323
324 if current_topic != required_topic:
325 try:
326 if not module.check_mode:
327 request_kwargs = {
328 "Identity": identity,
329 "NotificationType": notification_type,
330 "aws_retry": True,
331 }
332
333 # The topic has to be omitted from the request to disable the notification.
334 if required_topic is not None:
335 request_kwargs["SnsTopic"] = required_topic
336
337 connection.set_identity_notification_topic(**request_kwargs)
338 except (BotoCoreError, ClientError) as e:
339 module.fail_json_aws(
340 e,
341 msg=f"Failed to set identity notification topic for {identity} {notification_type}",
342 )
343 return True
344 return False
345
346
347 def update_notification_topic_headers(connection, module, identity, identity_notifications, notification_type):
348 arg_dict = module.params.get(notification_type.lower() + "_notifications")
349 header_key = "HeadersIn" + notification_type + "NotificationsEnabled"
350 if identity_notifications is None:
351 # If there is no configuration for topic notifications, headers cannot be being
352 # forwarded, hence assume false.
353 current = False
354 elif header_key in identity_notifications:
355 current = identity_notifications[header_key]
356 else:
357 # AWS API doc indicates that the headers in fields are optional. Unfortunately
358 # it's not clear on what this means. But it's a pretty safe assumption that it means
359 # headers are not included since most API consumers would interpret absence as false.
360 current = False
361
362 if arg_dict is not None and "include_headers" in arg_dict:
363 required = arg_dict["include_headers"]
364 else:
365 required = False
366
367 if current != required:
368 try:
369 if not module.check_mode:
370 connection.set_identity_headers_in_notifications_enabled(
371 Identity=identity, NotificationType=notification_type, Enabled=required, aws_retry=True
372 )
373 except (BotoCoreError, ClientError) as e:
374 module.fail_json_aws(
375 e, msg=f"Failed to set identity headers in notification for {identity} {notification_type}"
376 )
377 return True
378 return False
379
380
381 def update_feedback_forwarding(connection, module, identity, identity_notifications):
382 if identity_notifications is None:
383 # AWS requires feedback forwarding to be enabled unless bounces and complaints
384 # are being handled by SNS topics. So in the absence of identity_notifications
385 # information existing feedback forwarding must be on.
386 current = True
387 elif "ForwardingEnabled" in identity_notifications:
388 current = identity_notifications["ForwardingEnabled"]
389 else:
390 # If there is information on the notifications setup but no information on the
391 # forwarding state it's pretty safe to assume forwarding is off. AWS API docs
392 # suggest this information will always be included but best to be defensive
393 current = False
394
395 required = module.params.get("feedback_forwarding")
396
397 if current != required:
398 try:
399 if not module.check_mode:
400 connection.set_identity_feedback_forwarding_enabled(
401 Identity=identity, ForwardingEnabled=required, aws_retry=True
402 )
403 except (BotoCoreError, ClientError) as e:
404 module.fail_json_aws(e, msg=f"Failed to set identity feedback forwarding for {identity}")
405 return True
406 return False
407
408
409 def create_mock_notifications_response(module):
410 resp = {
411 "ForwardingEnabled": module.params.get("feedback_forwarding"),
412 }
413 for notification_type in ("Bounce", "Complaint", "Delivery"):
414 arg_dict = module.params.get(notification_type.lower() + "_notifications")
415 if arg_dict is not None and "topic" in arg_dict:
416 resp[notification_type + "Topic"] = arg_dict["topic"]
417
418 header_key = "HeadersIn" + notification_type + "NotificationsEnabled"
419 if arg_dict is not None and "include_headers" in arg_dict:
420 resp[header_key] = arg_dict["include_headers"]
421 else:
422 resp[header_key] = False
423 return resp
424
425
426 def update_identity_notifications(connection, module):
427 identity = module.params.get("identity")
428 changed = False
429 identity_notifications = get_identity_notifications(connection, module, identity)
430
431 for notification_type in ("Bounce", "Complaint", "Delivery"):
432 changed |= update_notification_topic(connection, module, identity, identity_notifications, notification_type)
433 changed |= update_notification_topic_headers(
434 connection, module, identity, identity_notifications, notification_type
435 )
436
437 changed |= update_feedback_forwarding(connection, module, identity, identity_notifications)
438
439 if changed or identity_notifications is None:
440 if module.check_mode:
441 identity_notifications = create_mock_notifications_response(module)
442 else:
443 identity_notifications = get_identity_notifications(connection, module, identity, retries=4)
444 return changed, identity_notifications
445
446
447 def validate_params_for_identity_present(module):
448 if module.params.get("feedback_forwarding") is False:
449 if not (desired_topic(module, "Bounce") and desired_topic(module, "Complaint")):
450 module.fail_json(
451 msg=(
452 "Invalid Parameter Value 'False' for 'feedback_forwarding'. AWS requires "
453 "feedback forwarding to be enabled unless bounces and complaints are handled by SNS topics"
454 )
455 )
456
457
458 def create_or_update_identity(connection, module, region, account_id):
459 identity = module.params.get("identity")
460 changed = False
461 verification_attributes = get_verification_attributes(connection, module, identity)
462 if verification_attributes is None:
463 try:
464 if not module.check_mode:
465 if "@" in identity:
466 connection.verify_email_identity(EmailAddress=identity, aws_retry=True)
467 else:
468 connection.verify_domain_identity(Domain=identity, aws_retry=True)
469 except (BotoCoreError, ClientError) as e:
470 module.fail_json_aws(e, msg=f"Failed to verify identity {identity}")
471 if module.check_mode:
472 verification_attributes = {
473 "VerificationStatus": "Pending",
474 }
475 else:
476 verification_attributes = get_verification_attributes(connection, module, identity, retries=4)
477 changed = True
478 elif verification_attributes["VerificationStatus"] not in ("Pending", "Success"):
479 module.fail_json(
480 msg="Identity " + identity + " in bad status " + verification_attributes["VerificationStatus"],
481 verification_attributes=camel_dict_to_snake_dict(verification_attributes),
482 )
483
484 if verification_attributes is None:
485 module.fail_json(msg="Unable to load identity verification attributes after registering identity.")
486
487 notifications_changed, notification_attributes = update_identity_notifications(connection, module)
488 changed |= notifications_changed
489
490 if notification_attributes is None:
491 module.fail_json(msg="Unable to load identity notification attributes.")
492
493 identity_arn = "arn:aws:ses:" + region + ":" + account_id + ":identity/" + identity
494
495 module.exit_json(
496 changed=changed,
497 identity=identity,
498 identity_arn=identity_arn,
499 verification_attributes=camel_dict_to_snake_dict(verification_attributes),
500 notification_attributes=camel_dict_to_snake_dict(notification_attributes),
501 )
502
503
504 def destroy_identity(connection, module):
505 identity = module.params.get("identity")
506 changed = False
507 verification_attributes = get_verification_attributes(connection, module, identity)
508 if verification_attributes is not None:
509 try:
510 if not module.check_mode:
511 connection.delete_identity(Identity=identity, aws_retry=True)
512 except (BotoCoreError, ClientError) as e:
513 module.fail_json_aws(e, msg=f"Failed to delete identity {identity}")
514 changed = True
515
516 module.exit_json(
517 changed=changed,
518 identity=identity,
519 )
520
521
522 def get_account_id(module):
523 sts = module.client("sts")
524 try:
525 caller_identity = sts.get_caller_identity()
526 except (BotoCoreError, ClientError) as e:
527 module.fail_json_aws(e, msg="Failed to retrieve caller identity")
528 return caller_identity["Account"]
529
530
531 def main():
532 module = AnsibleAWSModule(
533 argument_spec={
534 "identity": dict(required=True, type="str"),
535 "state": dict(default="present", choices=["present", "absent"]),
536 "bounce_notifications": dict(type="dict"),
537 "complaint_notifications": dict(type="dict"),
538 "delivery_notifications": dict(type="dict"),
539 "feedback_forwarding": dict(default=True, type="bool"),
540 },
541 supports_check_mode=True,
542 )
543
544 for notification_type in ("bounce", "complaint", "delivery"):
545 param_name = notification_type + "_notifications"
546 arg_dict = module.params.get(param_name)
547 if arg_dict:
548 extra_keys = [x for x in arg_dict.keys() if x not in ("topic", "include_headers")]
549 if extra_keys:
550 module.fail_json(
551 msg="Unexpected keys "
552 + str(extra_keys)
553 + " in "
554 + param_name
555 + " valid keys are topic or include_headers"
556 )
557
558 # SES APIs seem to have a much lower throttling threshold than most of the rest of the AWS APIs.
559 # Docs say 1 call per second. This shouldn't actually be a big problem for normal usage, but
560 # the ansible build runs multiple instances of the test in parallel that's caused throttling
561 # failures so apply a jittered backoff to call SES calls.
562 connection = module.client("ses", retry_decorator=AWSRetry.jittered_backoff())
563
564 state = module.params.get("state")
565
566 if state == "present":
567 region = module.region
568 account_id = get_account_id(module)
569 validate_params_for_identity_present(module)
570 create_or_update_identity(connection, module, region, account_id)
571 else:
572 destroy_identity(connection, module)
573
574
575 if __name__ == "__main__":
576 main()