
    Vh]                         d Z dZdZddlZ	 ddlmZ ddlmZ ddlm	Z	 ddl
mZ dd	lmZ dd
ZddZd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zedk(  r e        yy# e$ r Y Pw xY w)aK  
---
module: ses_identity
version_added: 1.0.0
short_description: Manages SES email and domain identity
description:
    - This module allows the user to manage verified email and domain identity for SES.
    - This covers verifying and removing identities as well as setting up complaint, bounce
      and delivery notification settings.
    - Prior to release 5.0.0 this module was called C(community.aws.aws_ses_identity).
      The usage did not change.
author:
    - Ed Costello (@orthanc)
options:
    identity:
        description:
            - This is the email address or domain to verify / delete.
            - If this contains an '@' then it will be considered an email. Otherwise it will be considered a domain.
        required: true
        type: str
    state:
        description: Whether to create(or update) or delete the identity.
        default: present
        choices: [ 'present', 'absent' ]
        type: str
    bounce_notifications:
        description:
            - Setup the SNS topic used to report bounce notifications.
            - If omitted, bounce notifications will not be delivered to a SNS topic.
            - If bounce notifications are not delivered to a SNS topic, I(feedback_forwarding) must be enabled.
        suboptions:
            topic:
                description:
                    - The ARN of the topic to send notifications to.
                    - If omitted, notifications will not be delivered to a SNS topic.
            include_headers:
                description:
                    - Whether or not to include headers when delivering to the SNS topic.
                    - If I(topic) is not specified this will have no impact, but the SES setting is updated even if there is no topic.
                type: bool
                default: No
        type: dict
    complaint_notifications:
        description:
            - Setup the SNS topic used to report complaint notifications.
            - If omitted, complaint notifications will not be delivered to a SNS topic.
            - If complaint notifications are not delivered to a SNS topic, I(feedback_forwarding) must be enabled.
        suboptions:
            topic:
                description:
                    - The ARN of the topic to send notifications to.
                    - If omitted, notifications will not be delivered to a SNS topic.
            include_headers:
                description:
                    - Whether or not to include headers when delivering to the SNS topic.
                    - If I(topic) is not specified this will have no impact, but the SES setting is updated even if there is no topic.
                type: bool
                default: No
        type: dict
    delivery_notifications:
        description:
            - Setup the SNS topic used to report delivery notifications.
            - If omitted, delivery notifications will not be delivered to a SNS topic.
        suboptions:
            topic:
                description:
                    - The ARN of the topic to send notifications to.
                    - If omitted, notifications will not be delivered to a SNS topic.
            include_headers:
                description:
                    - Whether or not to include headers when delivering to the SNS topic.
                    - If I(topic) is not specified this will have no impact, but the SES setting is updated even if there is no topic.
                type: bool
                default: No
        type: dict
    feedback_forwarding:
        description:
            - Whether or not to enable feedback forwarding.
            - This can only be false if both I(bounce_notifications) and I(complaint_notifications) specify SNS topics.
        type: 'bool'
        default: true
extends_documentation_fragment:
    - amazon.aws.common.modules
    - amazon.aws.region.modules
    - amazon.aws.boto3
ab  
# Note: These examples do not set authentication details, see the AWS Guide for details.

- name: Ensure example@example.com email identity exists
  community.aws.ses_identity:
    identity: example@example.com
    state: present

- name: Delete example@example.com email identity
  community.aws.ses_identity:
    email: example@example.com
    state: absent

- name: Ensure example.com domain identity exists
  community.aws.ses_identity:
    identity: example.com
    state: present

# Create an SNS topic and send bounce and complaint notifications to it
# instead of emailing the identity owner
- name: Ensure complaints-topic exists
  community.aws.sns_topic:
    name: "complaints-topic"
    state: present
    purge_subscriptions: false
  register: topic_info

- name: Deliver feedback to topic instead of owner email
  community.aws.ses_identity:
    identity: example@example.com
    state: present
    complaint_notifications:
      topic: "{{ topic_info.sns_arn }}"
      include_headers: true
    bounce_notifications:
      topic: "{{ topic_info.sns_arn }}"
      include_headers: false
    feedback_forwarding: false

# Create an SNS topic for delivery notifications and leave complaints
# Being forwarded to the identity owner email
- name: Ensure delivery-notifications-topic exists
  community.aws.sns_topic:
    name: "delivery-notifications-topic"
    state: present
    purge_subscriptions: false
  register: topic_info

- name: Delivery notifications to topic
  community.aws.ses_identity:
    identity: example@example.com
    state: present
    delivery_notifications:
      topic: "{{ topic_info.sns_arn }}"
ai
  
identity:
    description: The identity being modified.
    returned: success
    type: str
    sample: example@example.com
identity_arn:
    description: The arn of the identity being modified.
    returned: success
    type: str
    sample: arn:aws:ses:us-east-1:12345678:identity/example@example.com
verification_attributes:
    description: The verification information for the identity.
    returned: success
    type: complex
    sample: {
        "verification_status": "Pending",
        "verification_token": "...."
    }
    contains:
        verification_status:
            description: The verification status of the identity.
            type: str
            sample: "Pending"
        verification_token:
            description: The verification token for a domain identity.
            type: str
notification_attributes:
    description: The notification setup for the identity.
    returned: success
    type: complex
    sample: {
        "bounce_topic": "arn:aws:sns:....",
        "complaint_topic": "arn:aws:sns:....",
        "delivery_topic": "arn:aws:sns:....",
        "forwarding_enabled": false,
        "headers_in_bounce_notifications_enabled": true,
        "headers_in_complaint_notifications_enabled": true,
        "headers_in_delivery_notifications_enabled": true
    }
    contains:
        bounce_topic:
            description:
              - The ARN of the topic bounce notifications are delivered to.
              - Omitted if bounce notifications are not delivered to a topic.
            type: str
        complaint_topic:
            description:
              - The ARN of the topic complaint notifications are delivered to.
              - Omitted if complaint notifications are not delivered to a topic.
            type: str
        delivery_topic:
            description:
              - The ARN of the topic delivery notifications are delivered to.
              - Omitted if delivery notifications are not delivered to a topic.
            type: str
        forwarding_enabled:
            description: Whether or not feedback forwarding is enabled.
            type: bool
        headers_in_bounce_notifications_enabled:
            description: Whether or not headers are included in messages delivered to the bounce topic.
            type: bool
        headers_in_complaint_notifications_enabled:
            description: Whether or not headers are included in messages delivered to the complaint topic.
            type: bool
        headers_in_delivery_notifications_enabled:
            description: Whether or not headers are included in messages delivered to the delivery topic.
            type: bool
    N)BotoCoreError)ClientError)camel_dict_to_snake_dict)AWSRetry)AnsibleCommunityAWSModulec                    t        d|dz         D ]7  }	 | j                  |gd      }d   }||v r nt        j                  |       9 |vry ||   S # t        t        f$ r }|j	                  |d|        Y d }~Vd }~ww xY w)Nr      T
Identities	aws_retryz8Failed to retrieve identity verification attributes for msgVerificationAttributes)range$get_identity_verification_attributesr   r   fail_json_awstimesleep)	
connectionmoduleidentityretries
retryDelayattemptresponseeidentity_verifications	            n/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/aws/plugins/modules/ses_identity.pyget_verification_attributesr      s     GaK( 	o!FFS[R\hlFmH !))A B,,

: ,, ** {+ 	o  *bckbl(m nn	os   AB#A>>Bc                    t        d|dz         D ]u  }	 | j                  |gd      }d   }||v r nUt        |      dk7  r0|j                  dj                  ||j                                      t        j                  |       w |vry ||   S # t        t        f$ r }|j	                  |d|        Y d }~d }~ww xY w)	Nr   r	   Tr
   z8Failed to retrieve identity notification attributes for r   NotificationAttributeszQUnexpected identity found in notification attributes, expected {0} but got {1!r}.)r   $get_identity_notification_attributesr   r   r   len	fail_jsonformatkeysr   r   )	r   r   r   r   r   r   r   r   notification_attributess	            r   get_identity_notificationsr(      s     GaK( 	o!FFS[R\hlFmH #++C"D .. &'1,gnn+002   	

:78 .."8,,7 {+ 	o  *bckbl(m nn	os   BC!B<<Cc                     | j                   j                  |j                         dz         }|r|j                  dd       S y )N_notificationstopicparamsgetlower)r   notification_typearg_dicts      r   desired_topicr2   '  s=    }}  !2!8!8!:=M!MNH||GT**    c                 p   |j                   j                  |j                          d      y|dz   }|d }n||v r||   }nd }t        ||      }||k7  r-	 |j                  s||dd}|||d<    | j
                  d
i | yy# t        t        f$ r#}	|j                  |	d| d| 	       Y d }	~	yd }	~	ww xY w)Nr*   FTopicT)IdentityNotificationTyper   SnsTopicz.Failed to set identity notification topic for  r    )	r-   r.   r/   r2   
check_modeset_identity_notification_topicr   r   r   )
r   r   r   identity_notificationsr0   	topic_keycurrent_topicrequired_topicrequest_kwargsr   s
             r   update_notification_topicrB   /  s   }}-3356nEFN!G+I% 	,	,.y9 "6+<=N&	$$ ((9!%" "-1?N:.:
::L^L  {+ 	  DXJaPaObc !   	s   +B B5B00B5c                 d   |j                   j                  |j                         dz         }d|z   dz   }|d}n||v r||   }nd}|
d|v r|d   }nd}||k7  r#	 |j                  s| j	                  |||d       yy# t
        t        f$ r#}	|j                  |	d| d	| 
       Y d }	~	yd }	~	ww xY w)Nr*   	HeadersInNotificationsEnabledFinclude_headersT)r6   r7   Enabledr   z3Failed to set identity headers in notification for r9   r   )r-   r.   r/   r;   -set_identity_headers_in_notifications_enabledr   r   r   )
r   r   r   r=   r0   r1   
header_keycurrentrequiredr   s
             r   !update_notification_topic_headersrL   [  s   }}  !2!8!8!:=M!MNH003IIJ% 	-	-(4
  1X =-.(	$$HH%8IS[gk I   {+ 	  LXJVWXiWjk !   		s   !A= =B/B**B/c                    |d}nd|v r|d   }nd}|j                   j                  d      }||k7  r"	 |j                  s| j                  ||d       yy# t        t
        f$ r }|j                  |d|        Y d }~yd }~ww xY w)NTForwardingEnabledFfeedback_forwarding)r6   rN   r   z/Failed to set identity feedback forwarding for r   )r-   r.   r;   (set_identity_feedback_forwarding_enabledr   r   r   )r   r   r   r=   rJ   rK   r   s          r   update_feedback_forwardingrQ   }  s    % 	 6	6()<=
 }}  !67H(	f$$CC%T D 
  {+ 	f  *YZbYc(d ee	fs    A B$A??Bc                     d| j                   j                  d      i}dD ][  }| j                   j                  |j                         dz         }|d|v r|d   ||dz   <   d|z   dz   }|d	|v r	|d	   ||<   Wd
||<   ] |S )NrN   rO   Bounce	ComplaintDeliveryr*   r+   r5   rD   rE   rF   Fr,   )r   respr0   r1   rI   s        r   "create_mock_notifications_responserX     s    V]]../DED A 	%==$$%6%<%<%>AQ%QRGx$7080AD"W,- #447MM
$5$A'(9:D$D	% Kr3   c           	      2   |j                   j                  d      }d}t        | ||      }dD ]&  }|t        | ||||      z  }|t	        | ||||      z  }( |t        | |||      z  }|s|*|j                  rt        |      }||fS t        | ||d      }||fS )Nr   FrS      r   )r-   r.   r(   rB   rL   rQ   r;   rX   )r   r   r   changedr=   r0   s         r   update_identity_notificationsr]     s    }}  ,HG7
FHU@ 
,ZKactuu4*@BS
 	

 )*fhH^__G(0%G%O" *** &@
FT\fg%h"***r3   c                     | j                   j                  d      du r,t        | d      rt        | d      s| j                  d       y y y )NrO   FrT   rU   zInvalid Parameter Value 'False' for 'feedback_forwarding'. AWS requires feedback forwarding to be enabled unless bounces and complaints are handled by SNS topicsr   )r-   r.   r2   r$   )r   s    r   $validate_params_for_identity_presentr_     sQ    }}./58fh/M&+4Vp   5W 9r3   c           	         |j                   j                  d      }d}t        | ||      }|[	 |j                  s+d|v r| j	                  |d       n| j                  |d       |j                  rd	d
i}nt        | ||d      }d}n/|d	   dvr(|j                  d|z   dz   |d	   z   t        |             ||j                  d       t        | |      \  }}	||z  }|	|j                  d       d|z   dz   |z   dz   |z   }
|j                  |||
t        |      t        |	             y # t        t        f$ r }|j                  |d|        Y d }~d }~ww xY w)Nr   F@T)EmailAddressr   )Domainr   zFailed to verify identity r   VerificationStatusPendingrZ   r[   )re   Successz	Identity z in bad status )r   verification_attributeszKUnable to load identity verification attributes after registering identity.z0Unable to load identity notification attributes.zarn:aws:ses::z
:identity/)r\   r   identity_arnrg   r'   )r-   r.   r   r;   verify_email_identityverify_domain_identityr   r   r   r$   r   r]   	exit_json)r   r   region
account_idr   r\   rg   r   notifications_changedr'   ri   s              r   create_or_update_identityrp     s   }}  ,HG9*fhW&	Q$$(?44(VZ4[55XQU5V $i'# 'B*fV^hi&j#	 !5	6>T	Th&)::=TUi=jj$<=T$U 	 	

 &jk5RS]_e5f22$$G&OP!F*S0:=LxWL
! 89P Q 89P Q  5 {+ 	Q  *DXJ(O PP	Qs   7D- -E<EEc                 *   |j                   j                  d      }d}t        | ||      }|"	 |j                  s| j	                  |d       d}|j                  ||       y # t
        t        f$ r }|j                  |d|        Y d }~@d }~ww xY w)Nr   FT)r6   r   zFailed to delete identity r   )r\   r   )	r-   r.   r   r;   delete_identityr   r   r   rl   )r   r   r   r\   rg   r   s         r   destroy_identityrs     s    }}  ,HG9*fhW*	Q$$**H*M 
  	 {+ 	Q  *DXJ(O PP	Qs   A# #B2BBc                     | j                  d      }	 |j                         }|d   S # t        t        f$ r!}| j	                  |d       Y d }~d   S d }~ww xY w)Nstsz"Failed to retrieve caller identityr   Account)clientget_caller_identityr   r   r   )r   ru   caller_identityr   s       r   get_account_idrz   
  sl    
--
CJ113 9%% ;' JQ$HII9%%Js   ( AAAc                     t        t        dd      t        dddg      t        d      t        d      t        d      t        dd	
      dd      } dD ]q  }|dz   }| j                  j                  |      }|s&|j	                         D cg c]	  }|dvs| }}|sK| j                  dt        |      z   dz   |z   dz          s | j                  dt        j                               }| j                  j                  d      }|dk(  r1| j                  }t        |       }	t        |        t        || ||	       y t        ||        y c c}w )NTstr)rK   typepresentabsent)defaultchoicesdict)r}   bool)r   r}   )r   statebounce_notificationscomplaint_notificationsdelivery_notificationsrO   )argument_specsupports_check_mode)bounce	complaintdeliveryr*   )r+   rF   zUnexpected keys z in z( valid keys are topic or include_headersr   ses)retry_decoratorr   )AnsibleAWSModuler   r-   r.   r&   r$   r|   rw   r   jittered_backoffrm   rz   r_   rp   rs   )
r   r0   
param_namer1   x
extra_keysr   r   rm   rn   s
             r   mainr     s\   d7)i5JK$(f$5'+'8&*&7#'6#B
 !
F A &)99
==$$Z0%-]]_^A]8]!^J^  **o& !! A	A ! $ uh6O6O6QRJMMg&E	#F+
,V4!*ffjIV,1 _s   	EE__main__)r   
   )DOCUMENTATIONEXAMPLESRETURNr   botocore.exceptionsr   r   ImportError0ansible.module_utils.common.dict_transformationsr   ;ansible_collections.amazon.aws.plugins.module_utils.retriesr   >ansible_collections.community.aws.plugins.module_utils.modulesr   r   r   r(   r2   rB   rL   rQ   rX   r]   r_   rp   rs   rz   r   __name__r:   r3   r   <module>r      s   Un6pD
L 	1/ V P x+(%-P)XD8"+*+\$&)-X zF }
  		s   A! !A)(A)