
    VhRm                         d Z dZdZddl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
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lmZ ddlmZ  G d de      Zd Zedk(  r e        yy# e$ r Y kw xY w)a  
module: sns_topic
short_description: Manages AWS SNS topics and subscriptions
version_added: 1.0.0
description:
  - The M(community.aws.sns_topic) module allows you to create, delete, and manage subscriptions for AWS SNS topics.
author:
  - "Joel Thompson (@joelthompson)"
  - "Fernando Jose Pando (@nand0p)"
  - "Will Thames (@willthames)"
options:
  name:
    description:
      - The name or ARN of the SNS topic to manage.
    required: true
    type: str
  topic_type:
    description:
      - The type of topic that should be created. Either Standard for FIFO (first-in, first-out).
      - Some regions, including GovCloud regions do not support FIFO topics.
        Use a default value of  'standard' or omit the option if the region
        does not support FIFO topics.
    choices: ["standard", "fifo"]
    default: 'standard'
    type: str
    version_added: 2.0.0
  state:
    description:
      - Whether to create or destroy an SNS topic.
    default: present
    choices: ["absent", "present"]
    type: str
  display_name:
    description:
      - Display name of the topic.
    type: str
  policy:
    description:
      - Policy to apply to the SNS topic.
      - Policy body can be YAML or JSON.
      - This is required for certain use cases for example with S3 bucket notifications.
    type: dict
  delivery_policy:
    description:
      - Delivery policy to apply to the SNS topic.
    type: dict
    suboptions:
      http:
        description:
          - Delivery policy for HTTP(S) messages.
          - See U(https://docs.aws.amazon.com/sns/latest/dg/sns-message-delivery-retries.html)
            for more information.
        type: dict
        required: false
        suboptions:
          disableSubscriptionOverrides:
            description:
              - Applies this policy to all subscriptions, even if they have their own policies.
            type: bool
            required: false
          defaultThrottlePolicy:
            description:
              - Throttle the rate of messages sent to subsriptions.
            type: dict
            suboptions:
              maxReceivesPerSecond:
                description:
                  - The maximum number of deliveries per second per subscription.
                type: int
                required: true
            required: false
          defaultHealthyRetryPolicy:
            description:
              - Retry policy for HTTP(S) messages.
            type: dict
            required: true
            suboptions:
              minDelayTarget:
                description:
                 - The minimum delay for a retry.
                type: int
                required: true
              maxDelayTarget:
                description:
                 - The maximum delay for a retry.
                type: int
                required: true
              numRetries:
                description:
                 - The total number of retries.
                type: int
                required: true
              numMaxDelayRetries:
                description:
                 - The number of retries with the maximum delay between them.
                type: int
                required: true
              numMinDelayRetries:
                description:
                 - The number of retries with just the minimum delay between them.
                type: int
                required: true
              numNoDelayRetries:
                description:
                 - The number of retries to be performmed immediately.
                type: int
                required: true
              backoffFunction:
                description:
                 - The function for backoff between retries.
                type: str
                required: true
                choices: ['arithmetic', 'exponential', 'geometric', 'linear']
  subscriptions:
    description:
      - List of subscriptions to apply to the topic. Note that AWS requires
        subscriptions to be confirmed, so you will need to confirm any new
        subscriptions.
    suboptions:
      endpoint:
        description: Endpoint of subscription.
        required: true
      protocol:
        description: Protocol of subscription.
        required: true
      attributes:
        description: Attributes of subscription. Only supports RawMessageDelievery for SQS endpoints.
        default: {}
        version_added: "4.1.0"
    type: list
    elements: dict
    default: []
  purge_subscriptions:
    description:
      - "Whether to purge any subscriptions not listed here. NOTE: AWS does not
        allow you to purge any PendingConfirmation subscriptions, so if any
        exist and would be purged, they are silently skipped. This means that
        somebody could come back later and confirm the subscription. Sorry.
        Blame Amazon."
    default: true
    type: bool
  content_based_deduplication:
    description:
      - Whether to enable content-based deduplication for this topic.
      - Ignored unless I(topic_type=fifo).
      - Defaults to C(disabled).
    choices: ["disabled", "enabled"]
    type: str
    version_added: 5.3.0
notes:
  - Support for I(tags) and I(purge_tags) was added in release 5.3.0.
extends_documentation_fragment:
  - amazon.aws.common.modules
  - amazon.aws.region.modules
  - amazon.aws.tags.modules
  - amazon.aws.boto3
a8  

- name: Create alarm SNS topic
  community.aws.sns_topic:
    name: "alarms"
    state: present
    display_name: "alarm SNS topic"
    delivery_policy:
      http:
        defaultHealthyRetryPolicy:
          minDelayTarget: 2
          maxDelayTarget: 4
          numRetries: 9
          numMaxDelayRetries: 5
          numMinDelayRetries: 2
          numNoDelayRetries: 2
          backoffFunction: "linear"
        disableSubscriptionOverrides: true
        defaultThrottlePolicy:
          maxReceivesPerSecond: 10
    subscriptions:
      - endpoint: "my_email_address@example.com"
        protocol: "email"
      - endpoint: "my_mobile_number"
        protocol: "sms"

- name: Create a topic permitting S3 bucket notifications
  community.aws.sns_topic:
    name: "S3Notifications"
    state: present
    display_name: "S3 notifications SNS topic"
    policy:
      Id: s3-topic-policy
      Version: 2012-10-17
      Statement:
        - Sid: Statement-id
          Effect: Allow
          Resource: "arn:aws:sns:*:*:S3Notifications"
          Principal:
            Service: s3.amazonaws.com
          Action: sns:Publish
          Condition:
            ArnLike:
              aws:SourceArn: "arn:aws:s3:*:*:SomeBucket"

- name: Example deleting a topic
  community.aws.sns_topic:
    name: "ExampleTopic"
    state: absent
a  
sns_arn:
    description: The ARN of the topic you are modifying
    type: str
    returned: always
    sample: "arn:aws:sns:us-east-2:123456789012:my_topic_name"
sns_topic:
  description: Dict of sns topic details
  type: complex
  returned: always
  contains:
    attributes_set:
      description: list of attributes set during this run
      returned: always
      type: list
      sample: []
    check_mode:
      description: whether check mode was on
      returned: always
      type: bool
      sample: false
    content_based_deduplication:
      description: Whether or not content_based_deduplication was set
      returned: always
      type: str
      sample: disabled
      version_added: 5.3.0
    delivery_policy:
      description: Delivery policy for the SNS topic
      returned: when topic is owned by this AWS account
      type: str
      sample: >
        {"http":{"defaultHealthyRetryPolicy":{"minDelayTarget":20,"maxDelayTarget":20,"numRetries":3,"numMaxDelayRetries":0,
        "numNoDelayRetries":0,"numMinDelayRetries":0,"backoffFunction":"linear"},"disableSubscriptionOverrides":false}}
    display_name:
      description: Display name for SNS topic
      returned: when topic is owned by this AWS account
      type: str
      sample: My topic name
    name:
      description: Topic name
      returned: always
      type: str
      sample: ansible-test-dummy-topic
    owner:
      description: AWS account that owns the topic
      returned: when topic is owned by this AWS account
      type: str
      sample: '123456789012'
    policy:
      description: Policy for the SNS topic
      returned: when topic is owned by this AWS account
      type: str
      sample: >
        {"Version":"2012-10-17","Id":"SomePolicyId","Statement":[{"Sid":"ANewSid","Effect":"Allow","Principal":{"AWS":"arn:aws:iam::123456789012:root"},
        "Action":"sns:Subscribe","Resource":"arn:aws:sns:us-east-2:123456789012:ansible-test-dummy-topic","Condition":{"StringEquals":{"sns:Protocol":"email"}}}]}
    state:
      description: whether the topic is present or absent
      returned: always
      type: str
      sample: present
    subscriptions:
      description: List of subscribers to the topic in this AWS account
      returned: always
      type: list
      sample: []
    subscriptions_added:
      description: List of subscribers added in this run
      returned: always
      type: list
      sample: []
    subscriptions_confirmed:
      description: Count of confirmed subscriptions
      returned: when topic is owned by this AWS account
      type: str
      sample: '0'
    subscriptions_deleted:
      description: Count of deleted subscriptions
      returned: when topic is owned by this AWS account
      type: str
      sample: '0'
    subscriptions_existing:
      description: List of existing subscriptions
      returned: always
      type: list
      sample: []
    subscriptions_new:
      description: List of new subscriptions
      returned: always
      type: list
      sample: []
    subscriptions_pending:
      description: Count of pending subscriptions
      returned: when topic is owned by this AWS account
      type: str
      sample: '0'
    subscriptions_purge:
      description: Whether or not purge_subscriptions was set
      returned: always
      type: bool
      sample: true
    topic_arn:
      description: ARN of the SNS topic (equivalent to sns_arn)
      returned: when topic is owned by this AWS account
      type: str
      sample: arn:aws:sns:us-east-2:123456789012:ansible-test-dummy-topic
    topic_created:
      description: Whether the topic was created
      returned: always
      type: bool
      sample: false
    topic_deleted:
      description: Whether the topic was deleted
      returned: always
      type: bool
      sample: false
    N)parse_aws_arn)compare_policies)ansible_dict_to_boto3_tag_list)scrub_none_parameters)AnsibleCommunityAWSModule)canonicalize_endpoint)compare_delivery_policies)get_info)list_topic_subscriptions)list_topics)topic_arn_lookup)update_tagsc                   X    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zy)SnsTopicManagerz*Handles SNS Topic creation and destructionc                    |j                  d      | _        || _        || _        || _        || _        || _        || _        |rt        |      nd | _	        || _
        g | _        g | _        g | _        g | _        t               | _        |	| _        || _        || _        d| _        d| _        d | _        g | _        |
| _        || _        y )NsnsF)client
connectionmodulename
topic_typestatedisplay_namepolicyr   delivery_policysubscriptionssubscriptions_existingsubscriptions_deletedsubscriptions_addedsubscriptions_attributes_setdictdesired_subscription_attributespurge_subscriptionscontent_based_deduplication
check_modetopic_createdtopic_deleted	topic_arnattributes_settags
purge_tags)selfr   r   r   r   r   r   r   r   r#   r*   r+   r$   r%   s                 k/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/aws/plugins/modules/sns_topic.py__init__zSnsTopicManager.__init__g  s      !--.	$
(IX4_E^b*&(#%'"#% ,.)/3v,#6 +F($"" 	$    c                 .   i }g }| j                   dk(  r4d|d<   | j                  j                  d      s| j                  dz   | _        | j                  rt	        | j                        }| j
                  s3	 | j                  j                  | j                  ||      }d   | _        y	# t        j                  j                  t        j                  j                  f$ r4}| j                  j                  |d| j                          Y d }~qd }~ww xY w)
Nfifotrue	FifoTopic.fifo)Name
AttributesTagszCouldn't create topic msgTopicArnT)r   r   endswithr*   r   r%   r   create_topicbotocore
exceptionsClientErrorBotoCoreErrorr   fail_json_awsr(   )r,   
attributesr*   responsees        r-   _create_topiczSnsTopicManager._create_topic  s    
 ??f$&,J{#99%%g. II/	991$))<DW??77TYYS]dh7i &j1DN ''33X5H5H5V5VW W))!3I$))1U)VVWs   6(B) )7D *DDc                    d}	 | j                   j                  | j                        d   }| j                  rn| j                  d   k7  r\d}| j                  j                  d       | j                  s3	 | j                   j                  | j                  d| j                  	       | j                  rt        | j                  t!        j"                  d               rod}| j                  j                  d       | j                  sF	 | j                   j                  | j                  dt!        j$                  | j                        	       dv r|d   dk(  rx| j&                  rl| j&                  dv rdnd}||d   k7  rRd}| j                  j                  d       | j                  s)	 | j                   j                  | j                  d|	       | j(                  rd|vs,t+        | j(                  t!        j"                  |d               rqd}| j                  j                  d       | j                  sH	 | j                   j                  | j                  dt!        j$                  | j(                        	       |S |S # t        j                  j
                  t        j                  j                  f$ r5}| j                  j                  |d| j                          Y d }~d }~ww xY w# t        j                  j
                  t        j                  j                  f$ r(}| j                  j                  |d
       Y d }~d }~ww xY w# t        j                  j
                  t        j                  j                  f$ r(}| j                  j                  |d       Y d }~^d }~ww xY w# t        j                  j
                  t        j                  j                  f$ r(}| j                  j                  |d       Y d }~<d }~ww xY w# t        j                  j
                  t        j                  j                  f$ r(}| j                  j                  |d       Y d }~|S d }~ww xY w)NFr:   r6   z(Couldn't get topic attributes for topic r8   DisplayNameTr   )r:   AttributeNameAttributeValuezCouldn't set display namePolicyr   zCouldn't set topic policyr3   r2   enabledfalseContentBasedDeduplicationr$   z(Couldn't set content-based deduplicationDeliveryPolicyr   z"Couldn't set topic delivery policy)r   get_topic_attributesr(   r=   r>   r?   r@   r   rA   r   r)   appendr%   set_topic_attributesr   r   jsonloadsdumpsr$   r   r	   )r,   changedtopic_attributesrD   rL   s        r-   _set_topic_attrsz SnsTopicManager._set_topic_attrs  s   	j#CCT^^C\]ij !2!26F}6U!UG&&~6??ROO88!%}]a]n]n 9  ;;+DKKDTU]D^9_`G&&x0??ROO88!%xX\XbXbcgcncnXo 9  ++0@0MQW0W.. $ @ @I MfSZG*+FGG##**+HIe<<%)^^C^ov =  $44()=)=tzzJZ[kJl?mnG&&'89??[OO88!%&6'+zz$2F2F'G 9  wq ##//1D1D1R1RS 	jKK%%a/WX\XfXfWg-h%ii	j !++779L9L9Z9Z[ RKK--a5P-QQR !++779L9L9Z9Z[ RKK--a5P-QQR  %//;;X=P=P=^=^_ e11!9c1dde  !++779L9L9Z9Z[ [KK--a5Y-ZZ[sy   )J 52K0 	AM *(N4 8AP 7K-8*K((K-07M'M

M7N1	N,,N147P+PP7Q5Q00Q5c           	      r   d}t               }| j                  D cg c]  }|d   t        |d   |d         f }}t        | j                  | j
                  | j                        D ]  }|d   |d   f}|j                  |       | j                  s+||vs0|d   dvs8d}| j                  j                  |       | j                  rb	 | j                  j                  |d   	        t        |      j%                  |      D ]Z  \  }}d}| j&                  j                  ||f       | j                  r2	 | j                  j)                  | j                  ||       \ |S c c}w # t        j                  j                  t        j                  j                   f$ r(}| j
                  j#                  |d
       Y d }~\d }~ww xY w# t        j                  j                  t        j                  j                   f$ r5}| j
                  j#                  |d| j                          Y d }~-d }~ww xY w)NFprotocolendpointProtocolEndpointSubscriptionArnPendingConfirmationDeletedTr^   Couldn't unsubscribe from topicr8   )r:   r\   r]   zCouldn't subscribe to topic )setr   r   r   r   r   r(   addr#   r   rQ   r%   unsubscriber=   r>   r?   r@   rA   
differencer   	subscribe)	r,   rV   subscriptions_existing_listsubdesired_subscriptionssub_keyrD   rZ   r[   s	            r-   _set_topic_subszSnsTopicManager._set_topic_subs  s   &)e#bfbtbt!
[^S_3C
OS_UV!
 !
 ,DOOT[[$..Y 	\C:J8G'++G4((#88)*2TT**11':\33CHYDZ3[	\  #&&;"<"G"GHc"d 	fHhG$$++Xx,@A??fOO--t~~PXck-l	f 9!
" %//;;X=P=P=^=^_ \11!9Z1[[\ !++779L9L9Z9Z[ fKK--a7STXTbTbSc5d-eefs5   E#	E(7(G
(7GGG
7H6*H11H6c                     | j                   D ]`  }|d   t        |d   |d         f}|j                  di       }|j                         D ]  \  }}t	        |      ||<    || j
                  |<   b y )NrZ   r[   rB   )r   r   getitemsstrr"   )r,   rj   rl   tmp_dictkvs         r-   %_init_desired_subscription_attributesz5SnsTopicManager._init_desired_subscription_attributes  s    %% 	EC:(=c*osS](_`Gww|R0H !( %1!!f% =ED009	Er/   c                 z   d}t        | j                  | j                  | j                        D ]  }|d   |d   f}|d   }| j                  j                  |      s.	 | j                  j                  |      d   }| j                  |   j                  d      }|odv st|d   j                         |j                         k7  sd	}| j                  r	 | j                  j                  |d|
        |S # t        j                  j                  t        j                  j                  f$ r)}| j                  j                  |d|        Y d }~d }~ww xY w# t        j                  j                  t        j                  j                  f$ r'}| j                  j                  |d       Y d }~d }~ww xY w)NFr\   r]   r^   rb   r6   z6Couldn't get subscription attributes for subscription RawMessageDeliveryT)r^   rI   rJ   z6Couldn't set RawMessageDelivery subscription attribute)r   r   r   r(   r"   ro   get_subscription_attributesr=   r>   r?   r@   rA   lowerr%   set_subscription_attributes)r,   rV   rj   rl   sub_arnsub_current_attributesrD   raw_messages           r-   _set_topic_subs_attributesz*SnsTopicManager._set_topic_subs_attributes  s   +DOOT[[$..Y 	sC:J8G+,G77;;GDq)-)T)Tel)T)m *& >>wGKKL`aK&+?CY+Y)*>?EEG;K\K\K^^"G??s OOGG07G[lw H )	s4  ''33X5H5H5V5VW q))!/efmen-oppq !) 3 3 ? ?ATATAbAbc s KK55a9qrrss0   C9E97E0EE7F:F55F:c                    t        | j                  | j                  | j                        }|sy|D ]U  }|d   dvs| j                  j                  |d          | j                  r6	 | j                  j                  |d          W y# t        j                  j                  t        j                  j                  f$ r'}| j                  j                  |d       Y d }~d }~ww xY w)NFr^   r_   rb   rc   r8   T)r   r   r   r(   r   rQ   r%   rf   r=   r>   r?   r@   rA   )r,   r   rj   rD   s       r-   _delete_subscriptionsz%SnsTopicManager._delete_subscriptions-  s     1$++t~~^  	\C$%-OO**11#6G2HI\33CHYDZ3[	\  %//;;X=P=P=^=^_ \11!9Z1[[\s   (B

7C(C##C(c                 V   d| _         | j                  s(	 | j                  j                  | j                         yy# t
        j                  j                  t
        j                  j                  f$ r4}| j                  j                  |d| j                          Y d }~yd }~ww xY w)NTrG   zCouldn't delete topic r8   )r'   r%   r   delete_topicr(   r=   r>   r?   r@   r   rA   )r,   rD   s     r-   _delete_topiczSnsTopicManager._delete_topic=  s    !\,,dnn,E  ''33X5H5H5V5VW \))!3I$..IY1Z)[[\s   &= 7B(4*B##B(c                 >    t        t        | j                              S )N)boolr   r   )r,   s    r-   _name_is_arnzSnsTopicManager._name_is_arnF  s    M$)),--r/   c                    d}| j                          | j                  s| j                         }| j                  t        | j                  | j
                        v r|| j                         z  }n@| j                  s| j                  s| j                  r| j
                  j                  d       || j                         z  }| j                          | j                  t        | j                  | j
                        v r|| j                         z  }n?t        | j                  j!                               r| j
                  j                  d       |t#        | j                  | j
                  | j                        z  }|S )NFz[Cannot set display name, policy or delivery policy for SNS topics not owned by this accountr8   zKCannot set subscription attributes for SNS topics not owned by this account)populate_topic_arnr(   rE   r   r   r   rX   r   r   r   	fail_jsonrm   ru   r~   anyr"   valuesr   r,   rV   s     r-   	ensure_okzSnsTopicManager.ensure_okI  s'   !~~((*G>>[$++FFt,,..G$++1E1EKK!!q "  	4''))224>>[$++FFt6688G55<<>?KK!!&s!t;tT^^LLr/   c                    d}| j                          | j                  rk| j                  t        | j                  | j                        vr| j                  j                  d       | j                         }|| j                         z  }|S )NFzOCannot use state=absent with third party ARN. Use subscribers=[] to unsubscriber8   )r   r(   r   r   r   r   r   r   r   s     r-   ensure_gonezSnsTopicManager.ensure_gone_  sw    !>>~~[$++%NN%%i &  002Gt))++Gr/   c                     | j                         r| j                  | _        y | j                  }| j                  dk(  r|j	                  d      s|dz  }t        | j                  | j                  |      | _        y )Nr1   r4   )r   r   r(   r   r;   r   r   r   )r,   r   s     r-   r   z"SnsTopicManager.populate_topic_arnk  s]    !YYDNyy??f$T]]7-CGOD)$//4;;Mr/   N)__name__
__module____qualname____doc__r.   rE   rX   rm   ru   r~   r   r   r   r   r   r    r/   r-   r   r   d  sF    4&%P,<|B	E< .,
Nr/   r   c                  B   t        t        dd      t        dd      t        dd      t        dd      t        dd      t        dd      t        ddg d            } t        t        dd| 	      t        d
d      t        ddt        t        dd            	            }t        t        dd|	            }t        t        d      t        ddddg      t        dddg      t               t        d      t        d|      t        g dd      t        d
d      t        ddg      t        d
d      t        ddg             }t        |d!      }|j                  j                  d"      }|j                  j                  d#      }|j                  j                  d$      }|j                  j                  d%      }|j                  j                  d&      }	|j                  j                  d'      }
|j                  j                  d(      }|j                  j                  d)      }|j                  j                  d*      }|j                  }|j                  j                  d+      }|j                  j                  d,      }t        ||||||	|
||||||      }|dk(  r|j                         }n|dk(  r|j                         }t        |j                  t        |j                  ||j                        -      } |j                  d.i | y )/NintT)typerequiredrq   )
arithmeticexponential	geometriclinear)r   r   choices)minDelayTargetmaxDelayTarget
numRetriesnumMaxDelayRetriesnumMinDelayRetriesnumNoDelayRetriesbackoffFunctionr!   )r   r   optionsr   F)maxReceivesPerSecond)defaultHealthyRetryPolicydisableSubscriptionOverridesdefaultThrottlePolicy)http)r   standardr1   )r   defaultr   presentabsent)r   r   )r   )r   r   list)r   r   elements)r   r   resource_tags)r   aliasesrL   disabled)r   )r   r   r   r   r   r   r   r#   r*   r+   r$   )argument_specsupports_check_moder   r   r   r   r   r   r   r#   r$   r*   r+   )rV   sns_arn	sns_topicr   )r!   AnsibleAWSModuleparamsro   r%   r   r   r   r(   r
   r   	exit_json)http_retry_argshttp_delivery_argsdelivery_argsr   r   r   r   r   r   r   r   r   r#   r$   r%   r*   r+   r   rV   	sns_factss                       r-   mainr   v  s    66UT2UT:UT:ED9%$@tuO "&FT?"[%)v%F"%)ut%D

 v7IJM 4 UJV@TU9y(.CDV &-@2FVD fd;v'89VT2$()Z1H$IM MtTF==V$D""<0JMMg&E==$$^4L]]x(Fmm''(9:OMM%%o6M --++,AB"(--"3"34Q"R""J==V$D""<0J#I  	%%'	(	'')##9//9L9LMI F!y!r/   __main__)DOCUMENTATIONEXAMPLESRETURNrS   r=   ImportError7ansible_collections.amazon.aws.plugins.module_utils.arnr   :ansible_collections.amazon.aws.plugins.module_utils.policyr   ;ansible_collections.amazon.aws.plugins.module_utils.taggingr   Bansible_collections.amazon.aws.plugins.module_utils.transformationr   >ansible_collections.community.aws.plugins.module_utils.modulesr   r   :ansible_collections.community.aws.plugins.module_utils.snsr   r	   r
   r   r   r   r   objectr   r   r   r   r/   r-   <module>r      s   \|1ft
l 	 R W f d x \ ` O _ R W RONf ONdS"l zF u  		s   A4 4A<;A<