
    Vh8                         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  G d d	      Zd
 Zedk(  r e        yy# e$ r Y 4w xY w)a
  
---
module: elb_instance
version_added: 1.0.0
short_description: De-registers or registers instances from EC2 ELBs
description:
  - This module de-registers or registers an AWS EC2 instance from the ELBs
    that it belongs to.
  - Will be marked changed when called only if there are ELBs found to operate on.
author:
  - "John Jarvis (@jarv)"
options:
  state:
    description:
      - Register or deregister the instance.
    required: true
    choices: ['present', 'absent']
    type: str
  instance_id:
    description:
      - EC2 Instance ID.
    required: true
    type: str
  ec2_elbs:
    description:
      - List of ELB names
      - Required when I(state=present).
    type: list
    elements: str
  enable_availability_zone:
    description:
      - Whether to enable the availability zone of the instance on the target ELB if the availability zone has not already
        been enabled.
      - If I(enable_availability_zone=no), the task will fail if the availability zone is not enabled on the ELB.
    type: bool
    default: true
  wait:
    description:
      - Wait for instance registration or deregistration to complete successfully before returning.
    type: bool
    default: true
  wait_timeout:
    description:
      - Number of seconds to wait for an instance to change state.
      - If I(wait_timeout=0) then this module may return an error if a transient error occurs.
      - If non-zero then any transient errors are ignored until the timeout is reached.
      - Ignored when I(wait=no).
    default: 0
    type: int
notes:
  - The ec2_elbs fact previously set by this module was deprecated in release 2.1.0 and since release
    4.0.0 is no longer set.
extends_documentation_fragment:
  - amazon.aws.common.modules
  - amazon.aws.region.modules
  - amazon.aws.boto3
a  
# basic pre_task and post_task example
pre_tasks:
  - name: Instance De-register
    community.aws.elb_instance:
      instance_id: "{{ ansible_ec2_instance_id }}"
      state: absent
    register: deregister_instances
    delegate_to: localhost
roles:
  - myrole
post_tasks:
  - name: Instance Register
    community.aws.elb_instance:
      instance_id: "{{ ansible_ec2_instance_id }}"
      ec2_elbs: "{{ deregister_instances.updated_elbs }}"
      state: present
    delegate_to: localhost
z
updated_elbs:
  description: A list of ELB names that the instance has been added to or removed from.
  returned: always
  type: list
  elements: str
    N)is_boto3_error_code)AWSRetry)AnsibleCommunityAWSModulec                   ~    e Zd ZdZddZd Zd Z ej                         d        Z	d Z
d Zd	 Zd
 ZddZd Zd Zy)
ElbManagerz9Handles EC2 instance ELB registration and de-registrationNc                 0   t        j                         }|| _        |j                  d|      | _        |j                  d|      | _        |j                  d|      | _        || _        | j                  |      | _	        d| _
        t               | _        y )Nautoscaling)retry_decoratorec2elbF)r   jittered_backoffmoduleclient
client_asg
client_ec2
client_elbinstance_id_get_instance_lbslbschangedsetupdated_elbs)selfr   r   ec2_elbsr
   s        n/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/aws/plugins/modules/elb_instance.py__init__zElbManager.__init__k   s~    "335 ---W ---O ---O&))(3E    c                    | j                   D ]  }|d   D cg c]  }|d   	 }}| j                  |vr'| j                  j                  |d          | j                  j
                  rd| _        c	 | j                  j                  d|d   d| j                  ig       d| _         |r%| j                   D ]  }| j                  |d	|        yyc c}w # t        j                  j                  t        j                  j                  f$ r3}| j                  j                  |d|| j                         Y d}~d}~ww xY w)
z_De-register the instance from all ELBs and wait for the ELB
        to report it out-of-service	Instances
InstanceIdLoadBalancerNameT	aws_retryr!   r   z0Failed to deregister instance from load balancerload_balancerinstanceNDeregistered)r   r   r   addr   
check_moder   r   'deregister_instances_from_load_balancerbotocore
exceptionsClientErrorBotoCoreErrorfail_json_aws_await_elb_instance_state)r   waittimeoutlbiinstance_idses          r   
deregisterzElbManager.deregisterv   sK    (( 	 B57_EAlOELE|3!!"%7"89{{%%#	GG"%'(:%; ,d.>.>?@ H   DL3	 6 hh L..r>7KL 5 F  ''33X5H5H5V5VW ))IY[fjfvfv *  s   C1.C7D?)D::D?c                    | j                   D ]  }|d   D cg c]  }|d   	 }}| j                  |v r'| j                  j                  |d          |r$| xj                  | j                  |      z  c_        | j                  j                  rd| _        	 | j                  j                  d|d   d| j                  ig       d| _         |r%| j                   D ]  }| j                  |d	|        yyc c}w # t        j                  j                  t        j                  j                  f$ r3}| j                  j                  |d|| j                         Y d}~d}~ww xY w)
zaRegister the instance for all ELBs and wait for the ELB
        to report the instance in-servicer   r    r!   Tr"   z.Failed to register instance with load balancerr$   N	InService)r   r   r   r(   r   _enable_availailability_zoner   r)   r   %register_instances_with_load_balancerr+   r,   r-   r.   r/   r0   )r   r1   enable_availability_zoner2   r3   r4   r5   r6   s           r   registerzElbManager.register   sg    (( 	 B57_EAlOELE</!!"%7"89' A A" EE{{%%#	EE"%'(:%; ,d.>.>?@ F   DL3	 6 hh I..r;HI 5 F& ''33X5H5H5V5VW ))GWYdhdtdt *  s   C6.C;;7E%2)E  E%c                     | j                   j                  d      } |j                  di |j                         }|d   S )Ndescribe_load_balancersLoadBalancerDescriptions )r   get_paginatorpaginatebuild_full_result)r   params	paginatorresultss       r   _describe_elbszElbManager._describe_elbs   sA    OO112KL	$)$$.v.@@B122r   c                 F    d}| j                   D ]  }|d   |k(  sd} |S  |S )z)Verify that the named ELB actually existsFr!   T)r   )r   lbtestfoundr3   s       r   existszElbManager.exists   s>     (( 	B$%/		 r   c                 ~   | j                         }|d   d   }||d   v ry| j                  j                  ry	 | j                  j	                  d|d   |g       y# t
        j                  j                  t
        j                  j                  f$ r)}| j                  j                  |d||	       Y d
}~yd
}~ww xY w)zEnable the current instance's availability zone in the provided lb.
        Returns True if the zone was enabled or False if no change was made.
        lb: load balancer	PlacementAvailabilityZoneAvailabilityZonesFTr!   )r#   r!   rP   z%Failed to enable AZ on load balancers)r%   zoneN)
_get_instancer   r)   r   +enable_availability_zones_for_load_balancerr+   r,   r-   r.   r/   )r   r3   r&   desired_zoner6   s        r   r:   z'ElbManager._enable_availailability_zone   s     %%',-?@2122;;!!	wOOGG!#$6!7#/. H   ##//1D1D1R1RS 	wKK%%a)P`biu%vv	ws   "A 7B<B77B<c                    | j                   j                  ry| j                  |      }||k(  ry|dk(  r| j                  j	                  d      }n_|dk(  r| j                  j	                  d      }n>|dk(  r| j                  j	                  d      }n| j                   j                  d|       	 j                  |d	   d
| j                  igd|d       y# t        j                  j                  $ r(}| j                   j                  |d|       Y d}~yd}~wt        j                  j                  t        j                  j                  f$ r(}| j                   j                  |d|       Y d}~yd}~ww xY w)zWait for an ELB to change stateNr9   instance_in_servicer'   instance_deregisteredOutOfServicez Could not wait for unknown state)msgawaited_stater!   r       )DelayMaxAttempts)r!   r   WaiterConfigz3Timeout waiting for instance to reach desired statez7Error while waiting for instance to reach desired state)r   r)   _get_instance_healthr   
get_waiter	fail_jsonr1   r   r+   r,   WaiterErrorr/   r-   r.   )r   r3   rZ   r2   initial_statewaiterr6   s          r   r0   z$ElbManager._await_elb_instance_state   st   ;;!!11"5M)K'__//0EFFn,__//0GHFn,__//0GHFKK!!&HXe!f	KK!#$6!7($*:*:;<'(A   	 "".. 	KK%%L\i &   	 ##//1D1D1R1RS 	KK%%P`m &   		s$   0'C E:5D:E:E55E:c                 \   	 | j                   j                  d|d   d| j                  ig      d   }sy|d
   d   S # t        d      $ r Y yt        j
                  j                  t        j
                  j                  f$ r'}| j                  j                  |d	       Y d}~sd}~ww xY w)zt
        Check instance health, should return status object or None under
        certain error conditions.
        Tr!   r    r"   InstanceStatesInvalidInstanceNzFailed to get instance healthrY   r   State)
r   describe_instance_healthr   r   r+   r,   r-   r.   r   r/   )r   r3   statusr6   s       r   r_   zElbManager._get_instance_health  s    
	N__==!#$6!7($*:*:;< >  	 F ay!! ##45 	++--
 	N KK%%a-L%MM		Ns   1> B+6B+B&&B+c                    t               }|s| j                         }|r||d<   	  | j                  di |}|rS g }D ]7  }|d   D cg c]  }|d   	 }}| j                  |v s'|j                  |       9 |S # t        j                  j
                  t        j                  j                  f$ r&}| j                  j                  |d       Y d}~d}~ww xY wc c}w )zReturns a list of ELBs attached to self.instance_id
        ec2_elbs: an optional list of elb names that will be used
                  for elb lookup instead of returning what elbs
                  are attached to self.instance_idLoadBalancerNamesz!Failed to describe load balancersNr   r    rA   )dict_get_auto_scaling_group_lbsrH   r+   r,   r-   r.   r   r/   r   append)	r   r   list_paramselbsr6   r   r3   r4   r5   s	            r   r   zElbManager._get_instance_lbs  s     f779H/7K+,	N&4&&55D K  	B57_EAlOELE</

2	
 
 ##//1D1D1R1RS 	NKK%%a)LMM	N Fs   A; 	C;7C2CCc                    	 | j                   j                  d| j                  g      d   }t              dkD  r| j                  j                  d       |sg S |d	   d
   }	 | j                   j                  d|g      d   }t        |      dk7  r| j                  j                  d       |d	   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)ztReturns a list of ELBs associated with self.instance_id
        indirectly through its auto scaling group membershipTr#   InstanceIdsAutoScalingInstancesFailed to describe ASG Instancerh   Nr[   z8Illegal state, expected one auto scaling group instance.r   AutoScalingGroupName)r#   AutoScalingGroupNamesAutoScalingGroupsz/Illegal state, expected one auto scaling group.rm   )r   describe_auto_scaling_instancesr   r+   r,   r-   r.   r   r/   lenra   describe_auto_scaling_groups)r   asg_instancesr6   asg_names       r   ro   z&ElbManager._get_auto_scaling_group_lbs>  sq   	P OOKKT-=-=,> L $&M }!KK!!&`!aI #$:;	P OOHHxj I !#M }"KK!!&W!XQ 344- ##//1D1D1R1RS 	PKK%%a-N%OO	P  ##//1D1D1R1RS 	PKK%%a-N%OO	Ps/   +B7 $!D 77D.DD7E6E11E6c                 2   	 | j                   j                  d| j                  g      }d   d   d   d   S # t        j                  j
                  t        j                  j                  f$ r'}| j                  j                  |d       Y d}~gd}~ww xY w)	z&Returns the description of an instanceTrt   rw   rh   NReservationsr   r   )	r   describe_instancesr   r+   r,   r-   r.   r   r/   )r   resultr6   s      r   rR   zElbManager._get_instance^  s    	P__77$UYUeUeTf7gF n%a(5a88 ##//1D1D1R1RS 	PKK%%a-N%OO	Ps   (8 7B/BB)NN)N)__name__
__module____qualname____doc__r   r7   r=   r   r   rH   rL   r:   r0   r_   r   ro   rR   rA   r   r   r   r   h   s\    C	"!LF ID X 3 !3
0"H"0>5@9r   r   c                     t        dddgdddid dddd	ddd
dddd
ddddd      } dddgfg}t        | |d      }|j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  d   }t        |||      }|/|D ]*  }	|j	                  |	      r|j                  d|	 d       , |j                  d   dk(  r|j                  |||       n$|j                  d   dk(  r|j                  ||       |j                  |j                  t        |j                               y )NTpresentabsent)requiredchoicesr   Fliststr)defaultr   typeelementsbool)r   r   r   )r   r   r   r   int)stater   r   r<   r1   wait_timeoutr   r   )argument_specrequired_ifsupports_check_moder1   r<   r   r   zELB z does not existrh   )r   r   )rn   AnsibleAWSModulerE   r   rL   ra   r=   r7   	exit_jsonr   r   r   )
r   r   r   r   r1   r<   r2   r   elb_manr   s
             r   mainr   g  sz   Y,AB&!ufRWX-1uf!UD&A"'AuEM 
)j\*K # F }}Z(H== D%}}-GHmmN+G--.Kh7G 	BC>>#&  tC5%@ A	B }}W*7A	w	8	+4)
'../  r   __main__)DOCUMENTATIONEXAMPLESRETURNr+   ImportError<ansible_collections.amazon.aws.plugins.module_utils.botocorer   ;ansible_collections.amazon.aws.plugins.module_utils.retriesr   >ansible_collections.community.aws.plugins.module_utils.modulesr   r   r   r   r   rA   r   r   <module>r      sk   8t(
	 ] P x|9 |9~(V zF g	  		s   9 A A