
    VhM                        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 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ee   fdZ 	 d&dedee   de	eeeef         de	e   fdZ!	 d'dede	eeef      de	e   de	eeef      fdZ" G d  d!      Z# G d" d#      Z$ G d$ d%      Z%y# e$ r Y w xY w)(    )deepcopy)WaiterError)Any)Dict)List)Optional)Tuple)camel_dict_to_snake_dict)AnsibleEC2Error)%create_transit_gateway_vpc_attachment)%delete_transit_gateway_vpc_attachment)describe_subnets)(describe_transit_gateway_vpc_attachments)ensure_ec2_tags)%modify_transit_gateway_vpc_attachment)AnsibleAWSModule)boto3_tag_list_to_ansible_dict)boto3_tag_specifications)!ansible_dict_to_boto3_filter_list)boto3_resource_to_ansible_dict)
get_waiterreturnc                  
    g dS )N)	availabledeletingfailedfailinginitiatingRequest	modifyingpendingAcceptancependingrollingBackrejected	rejecting r%       r/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/amazon/aws/plugins/module_utils/transitgateway.py
get_statesr(   $   s     r&   Nmodulesubnetssubnet_detailsc                 R   |sy |	 t        | t        |            }|D cg c]  }|j	                  d       }}t        t        |            dkD  r&|j                  dt        t        |            |       |d   S # t        $ r}|j                  |       Y d }~d }~ww xY wc c}w )N	SubnetIdsVpcId   z>Attachment subnets may only be in one VPC, multiple VPCs found)msgvpcsr*   r   )r   listr   fail_json_aws_errorgetlenset	fail_json)clientr)   r*   r+   esr2   s          r'   subnets_to_vpcr<   4   s     	*-fWNN %33qAEE'N3D3
3t9~Pc$i" 	 	
 7N  	*&&q))	* 4s   A= B$=	B!BB!filtersattachment_idc                     i }|r|g|d<   n|rt        |      |d<   	 t        | fi |}t	              dkD  rt        d      |r|d   S dS # t        $ r}|j                  |       Y d}~Ad}~ww xY w)aV  Find an existing transit gateway attachment based on filters or attachment ID.

    Args:
        client: The AWS client used to interact with the EC2 service.
        module: The Ansible module instance used for error handling.
        filters (Optional[Dict[str, Any]]): A dictionary of filters to apply when searching for attachments.
        attachment_id (Optional[str]): The ID of a specific attachment to find.

    Returns:
        Optional[Dict[str, Any]]: The found attachment details or None if not found.

    Raises:
        ValueError: If multiple attachments match the criteria.
    TransitGatewayAttachmentIdsFiltersNr0   z3Multiple matching attachments found, provide an ID.r   )r   r   r   r4   r6   
ValueError)r9   r)   r=   r>   paramsattachmentsr:   s          r'   find_existing_attachmentrE   K   s    $ F1>,-	=gFy&>vPP ;!NOO(;q>2d2  &""1%%&s   A 	A/A**A/c                   v    e Zd ZdededdfdZedeeef   fd       Z	deeef   defdZ
defd	Zd
eddfdZy)$TransitGatewayAttachmentStateManagerr)   r>   r   Nc                 .    || _         || _        || _        y N)r9   r)   r>   )selfr9   r)   r>   s       r'   __init__z-TransitGatewayAttachmentStateManager.__init__p   s    *r&   c                     i }t        d| j                  j                  j                  d            }| j                  j                  j                  d      |z  }t	        ||      }||d<   |S )N   wait_timeout)DelayMaxAttemptsWaiterConfig)minr)   rC   r5   dict)rJ   rC   delaymax_attemptsconfigs        r'   waiter_configz2TransitGatewayAttachmentStateManager.waiter_configu   sb    !#At{{))--n=>{{))--n=FE|<!'~r&   rC   c                    	 |j                  d      }|rt        |dg      |d<   	 t        | j                  fi |}d   | _        |d   S # t        $ r d}Y Fw xY w# t
        $ r%}| j                  j                  |       Y d}~Id}~ww xY w)a  
        Create a new transit gateway attachment.

        Args:
            params (Dict[str, Any]): A dictionary containing the parameters needed to
                create the transit gateway attachment.

        Returns:
            str: The ID of the newly created transit gateway attachment.

        Raises:
            AnsibleEC2Error: If there is an error while creating the VPC attachment,
                it will fail the module and provide an error message.
        TagsNtransit-gateway-attachment)typesTagSpecificationsTransitGatewayAttachmentId)	popKeyErrorr   r   r9   r   r)   r4   r>   )rJ   rC   tagsresponser:   s        r'   create_attachmentz6TransitGatewayAttachmentStateManager.create_attachment   s    	::f%D *B4PlOm*nF&'	/<T[[SFSH &&BC455  	D	  	/KK++A..	/s(   A A AA	B&BBc                     | j                   sy| j                  j                  s"	 t        | j                  | j                          yy# t
        $ r%}| j                  j                  |       Y d }~yd }~ww xY w)NFT)r>   r)   
check_moder   r9   r   r4   )rJ   r:   s     r'   delete_attachmentz6TransitGatewayAttachmentStateManager.delete_attachment   se     !!{{%%35dkk4CUCUV  # 3//223s    A 	A5A00A5desired_statec                    d| j                   gi}|j                  | j                         t        | j                  d|       }	  |j
                  di | y # t        $ r&}| j                  j                  |d       Y d }~y d }~ww xY w)Nr@   transit_gateway_vpc_attachment_z Timeout waiting for State changer%   )	r>   updaterW   r   r9   waitr   r)   fail_json_aws)rJ   rf   rC   waiterr:   s        r'   wait_for_state_changez:TransitGatewayAttachmentStateManager.wait_for_state_change   s    /$2D2D1EFd(()DKK+J=/)Z[	MFKK!&! 	MKK%%a)KLL	Ms   A 	B!BB)__name__
__module____qualname__r   strrK   propertyr   r   rW   rb   boolre   rm   r%   r&   r'   rG   rG   o   s    +'7 + +PT +
 tCH~  6S#X 63 6@4 	M3 	M4 	Mr&   rG   c                   :   e Zd Zdededeeef   ddfdZedeeef   fd       Z	ede
e   fd       Zede
e   fd	       Zdd
ee
e      deddfdZd Zd Zd ZdefdZdefdZd ZddZdedee   defdZd dee   dedefdZdeeef   deeef   fdZy)!AttachmentConfigurationManagerr)   r>   existingr   Nc                 n    || _         || _        || _        |xs i | _        i | _        g | _        g | _        y rI   )r9   r)   r>   rv   _resource_updates_subnets_to_add_subnets_to_remove)rJ   r9   r)   r>   rv   s        r'   rK   z'AttachmentConfigurationManager.__init__   s;    * B!#!"$r&   c                     | j                   S rI   )rx   rJ   s    r'   resource_updatesz/AttachmentConfigurationManager.resource_updates   s    %%%r&   c                     | j                   S rI   )ry   r|   s    r'   subnets_to_addz-AttachmentConfigurationManager.subnets_to_add   s    ###r&   c                     | j                   S rI   )rz   r|   s    r'   subnets_to_removez0AttachmentConfigurationManager.subnets_to_remove   s    &&&r&   r*   purgec                    |yt        | j                  j                  dg             }t        |      }|s|j                  |      }	 t	        | j
                  t        |            }t        | j
                  | j                  |      }| j                  d|d       |D cg c]  }|j                  d       }	}t        |	      t        t        |	            k7  r| j                  j                  d|	|	       t        |j                  |            | _        t        |j                  |            | _        | j                  dt        |             y# t        $ r&}| j                  j                  |       Y d}~d}~ww xY wc c}w )
aQ  
        Set or update the subnets associated with the transit gateway attachment.

        Args:
            subnets (Optional[List[str]]): A list of subnet IDs to associate with
                the attachment.
            purge (bool): If True, the existing subnets will be replaced with the
                specified subnets.
        Nr.   r-   r/   T)	immutableAvailabilityZoneIdz<Only one attachment subnet per availability zone may be set.)r1   availability_zonesr*   )r7   rv   r5   unionr   r9   r3   r   r)   r4   r<   _set_resource_valuer6   r8   
differencery   rz   )
rJ   r*   r   current_subnetsdesired_subnetsr+   r:   vpc_idr;   azss
             r'   set_subnetsz*AttachmentConfigurationManager.set_subnets   sS    ?dmm//R@Ag,-33ODO	/-dkkT/EZ[N  T[[/>Z  &D A 5CCqquu)*CCs8s3s8}$KK!!R#&& "   $O$>$>$OP"&'A'A/'R"S  d?.CD!  	/KK++A..	/ Ds    E "F	FE>>Fc                 &    | j                  d|      S )N
DnsSupport_set_optionrJ   values     r'   set_dns_supportz.AttachmentConfigurationManager.set_dns_support   s    e44r&   c                 &    | j                  d|      S )NIpv6Supportr   r   s     r'   set_ipv6_supportz/AttachmentConfigurationManager.set_ipv6_support   s    u55r&   c                 &    | j                  d|      S )NApplianceModeSupportr   r   s     r'   set_appliance_mode_supportz9AttachmentConfigurationManager.set_appliance_mode_support   s     6>>r&   tgw_idc                 &    | j                  d|      S )NTransitGatewayIdr   )rJ   r   s     r'   set_transit_gatewayz2AttachmentConfigurationManager.set_transit_gateway  s    ''(:FCCr&   r   c                 &    | j                  d|      S )Nr/   r   )rJ   r   s     r'   set_vpcz&AttachmentConfigurationManager.set_vpc  s    ''88r&   c                     t        | j                  j                  dd             }|rt        |      }ni ||}| j	                  d|       y )NrY   )r   rv   r5   r   r   )rJ   r`   
purge_tagscurrent_tagsdesired_tagss        r'   set_tagsz'AttachmentConfigurationManager.set_tags	  sI    5dmm6G6GPT6UV#D>L3l3d3L  6r&   c                 r    | j                   j                  ||      }| j                  j                  ||      S rI   )rv   r5   rx   )rJ   keydefaultdefault_values       r'   _get_resource_valuez2AttachmentConfigurationManager._get_resource_value  s1    ))#w7%%))#}==r&   namer   c                    |y|rdnd}t        | j                  j                  dt                           }|j	                  | j
                  j                  dt                            |||<   | j                  d|      S )a  
        Set a VPC attachment option to either enable or disable.

        Args:
            name (str): The name of the option to be updated.
            value (Optional[bool]): A boolean indicating whether to enable (True)
                or disable (False) the specified option. If None, no action is
                taken.

        Returns:
            bool: Returns True if the option was successfully set, or False if
            no update was made (because the value was None).
        FenabledisableOptions)r   rv   r5   rS   ri   rx   r   )rJ   r   r   optionss       r'   r   z*AttachmentConfigurationManager._set_option  sq     = "y4==,,Y?@t--11)TVDE''	7;;r&   descriptionr   c                     ||| j                  |      k(  ry|r1| j                  r%|xs |}| j                  j                  | d       || j                  |<   y)a  
        Set a value for a resource attribute and track changes.

        Args:
            key (str): The attribute key to be updated.
            value (Any): The new value to set for the specified key.
            description (Optional[str], optional): A human-readable description of the
                resource attribute.
            immutable (bool, optional): A flag indicating whether the attribute is
                immutable. If True, and the resource exists, an error will be raised
                if attempting to change the value. Defaults to False.

        Returns:
            bool: Returns True if the value was successfully set, or False if no
            update was made.
        Fz" can not be updated after creation)r1   T)r   rv   r)   r8   r}   )rJ   r   r   r   r   s        r'   r   z2AttachmentConfigurationManager._set_resource_value1  sa    " =ET%=%=c%BB%,KKK!!5W&X!Y%*c"r&   resourcec                 h    g d}|j                         D ci c]  \  }}||vs|| c}}S c c}}w )a  
        Filter out immutable resource attributes from the given resource dictionary.

        Args:
            resource (Dict[str, Any]): A dictionary representing the resource, which
                may contain various attributes, including both mutable and immutable ones.

        Returns:
            Dict[str, Any]: A new dictionary containing only the mutable attributes
            of the resource.
        )r   r/   
VpcOwnerIdStater.   CreationTimerY   )items)rJ   r   immutable_optionsr   r   s        r'   $filter_immutable_resource_attributeszCAttachmentConfigurationManager.filter_immutable_resource_attributesM  s6     v-5^^-=^zsEL]A]U
^^^s   ..)NTrI   NF)rn   ro   rp   r   rq   r   r   rK   rr   r}   r   r   r   r   rs   r   r   r   r   r   r   r   r   r   r   r   r%   r&   r'   ru   ru      sX   %'7 % %W[\_ad\dWe %jn % &$sCx. & & $S	 $ $ '49 ' ''E8DI#6 'Ed 'EVZ 'ER56?D# D9c 97>< <HTN <t <48C= \` mq 8_T#s(^ _PTUXZ]U]P^ _r&   ru   c            	           e Zd Z	 ddedeeef   dee   ddfdZdde	deeef   fdZ
d	 Zdd
Zdeeeeef      e	f   fdZddZdeeef   de	ddfdZd Zd Zy)"TransitGatewayVpcAttachmentManagerNr)   rv   r>   r   c                     || _         || _        || _        |xs i | _        i | _        d| _        t        |||      | _        t        ||||      | _	        y r   )
r9   r)   r>   rv   updatedchangedrG   state_managerru   config_manager)rJ   r9   r)   rv   r>   s        r'   rK   z+TransitGatewayVpcAttachmentManager.__init__^  sY     * BA&&R_`<VV]\der&   filter_immutablec                     t        | j                        }|j                  | j                  j                         |r| j                  j                  |      }|S )a1  Merge existing resource attributes with updates, optionally filtering out immutable attributes.

        Args:
            filter_immutable (bool): Whether to filter out immutable resource attributes. Defaults to True.

        Returns:
            Dict[str, Any]: The merged resource attributes.
        )r   rv   ri   r   r}   r   )rJ   r   r   s      r'   merge_resource_changesz9TransitGatewayVpcAttachmentManager.merge_resource_changesk  sI     DMM*++<<=**OOPXYHr&   c                    | j                   sy| j                  j                  | j                  j                        }| j                  j                  }| j                  j
                  }|s|s|sy|r||d<   |r||d<   | j                   |d<   | j                  j                  s	 t        | j                  fi | yy# t        $ r%}| j                  j                  |       Y d}~yd}~ww xY w)zApply configuration changes to the transit gateway attachment.

        Returns:
            bool: True if configuration changes were applied, False otherwise.
        FAddSubnetIdsRemoveSubnetIdsr]   NT)r>   r   r   r}   r   r   r)   rd   r   r9   r   r4   )rJ   updatesr   r   r:   s        r'   apply_configurationz6TransitGatewayVpcAttachmentManager.apply_configuration|  s     !!%%JJ4K^K^KoKop,,;; //AA ~6G&4GN#):G%&040B0B,-{{%%35dkkMWM  # 3//223s   $B< <	C*C%%C*c                    | j                   j                  | j                  j                  j	                  d             | j                   j                  | j                  j                  d   | j                  j                  j	                  dd             | j                   j                  | j                  j                  j	                  d             | j                   j                  | j                  j                  j	                  d             | j                   j                  | j                  j                  j	                  d             y)	z@Set configuration parameters for the transit gateway attachment.transit_gatewayr*   purge_subnetsTdns_supportipv6_supportappliance_mode_supportN)	r   r   r)   rC   r5   r   r   r   r   r|   s    r'   _set_configuration_parametersz@TransitGatewayVpcAttachmentManager._set_configuration_parameters  s    //0B0B0F0FGX0YZ''(:(:9(Et{{GYGYG]G]^mosGtu++DKK,>,>,B,B=,QR,,T[[-?-?-C-CN-ST66t{{7I7I7M7MNf7ghr&   c                 Z   | j                   j                  j                  d      }| j                   j                  j                  d      }| j                   j                  j                  d      r3d| j                   j                  d   i}|d}n|j                  |       |}|i |fS ||fS )zPrepare and return the tags and purge flag.

        Returns:
            Tuple[Optional[Dict[str, str]], bool]: A tuple containing the tags dictionary and the purge flag.
        r`   r   r   NameF)r)   rC   r5   ri   )rJ   r`   r   new_tagss       r'   _prepare_tagsz0TransitGatewayVpcAttachmentManager._prepare_tags  s     {{!!%%f-[[''++L9
;;!!&) 2 26 :;H|"
%D\rZ77tZ77r&   c                 "   | j                   j                  sr| j                  d      }| j                  j	                  |      | _        | j                   j                  j                  d      r| j                  j                  d       d| _	        y)z(Create a new transit gateway attachment.Fr   rj   r   TN)
r)   rd   r   r   rb   r>   rC   r5   rm   r   )rJ   rC   s     r'   _create_attachmentz5TransitGatewayVpcAttachmentManager._create_attachment  sn    {{%%00%0HF!%!3!3!E!Ef!MD{{!!%%f-""88Er&   r`   r   c           
      H   | j                   j                  d      dk(  r| j                  j                  d       nO| j                   j                  d      dk(  r1| j                  j                  dt        | j                         g       | j                         rGd| _        | j                  j                  j                  d      r| j                  j                  d       | xj                  t        | j                  | j                  | j                  d	||
      z  c_        y)z.Update an existing transit gateway attachment.r   r!   r   r   z&Deletion in progress, unable to update)r1   rD   Trj   rZ   )resource_typer`   r   N)rv   r5   r   rm   r)   r8   r   r   r   rC   r   r9   r>   rJ   r`   r   s      r'   _update_attachmentz5TransitGatewayVpcAttachmentManager._update_attachment  s    ==W%244[A]]w':5KK!!<;DMMJK "  ##%DL{{!!%%f-""88E 	KKKK6!
 	
r&   c                    | j                          | j                         \  }}| j                  j                  ||       | j                  s| j                          n| j                  ||       | j                  j                  r$t        | j                  d      dg      | _        yt        t        | j                  | j                  | j                              | _        y)zOCreate or modify a transit gateway attachment based on the provided parameters.Fr   rY   )ignore_list)r>   N)r   r   r   r   rv   r   r   r)   rd   r
   r   r   r   rE   r9   r>   r   s      r'   create_or_modify_attachmentz>TransitGatewayVpcAttachmentManager.create_or_modify_attachment  s     	**,  --/j 	$$T:6}}##%##D*5 ;;!!3++U+CRXQYDL :(dkkQUQcQcdDLr&   c                    | j                   j                  d      dk(  rH| j                  j                  j                  d      r| j                  j                  d       d| _        y| xj                  | j                  j                         z  c_        | j                  j                  j                  d      r| j                  j                  d       yy)zDelete attachmentr   r   rj   deletedFN)	rv   r5   r)   rC   r   rm   changer   re   r|   s    r'   re   z4TransitGatewayVpcAttachmentManager.delete_attachment  s    ==W%3{{!!%%f-""88CDKLLD..@@BBL{{!!%%f-""88C .r&   rI   )T)r   N)rn   ro   rp   r   r   rq   r   r   rK   rs   r   r   r   r	   r   r   r   r   re   r%   r&   r'   r   r   ]  s    imf.f:>sCx.fYabeYff	ft tCQTH~ "Bi8uXd38n%=t%CD 8&	
tCH~ 
4 
D 
66	Dr&   r   rI   )NN)&copyr   botocore.exceptionsr   ImportErrortypingr   r   r   r   r	   0ansible.module_utils.common.dict_transformationsr
   7ansible_collections.amazon.aws.plugins.module_utils.ec2r   r   r   r   r   r   r   ;ansible_collections.amazon.aws.plugins.module_utils.modulesr   ;ansible_collections.amazon.aws.plugins.module_utils.taggingr   r   Bansible_collections.amazon.aws.plugins.module_utils.transformationr   r   ;ansible_collections.amazon.aws.plugins.module_utils.waitersr   rq   r(   r<   rE   rG   ru   r   r%   r&   r'   <module>r      s7   	/      U S i i T l S i X f ` p m RDI " lp$/3CyJRSWX\]`be]eXfSgJhc]0 pt!3$!3/7S#X/G!3_ghk_l!3d38n!3HHM HMV`_ `_FeD eDg
  		s   C( (C0/C0