U
    W+d                    @   s  d Z ddlZddlZddlmZ ddlm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mZmZ dd	lmZmZ dd
lmZmZ ddlmZ ddlmZ ddlmZ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l0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7 ddl8m9Z9 dd l:m;Z; dd!l<m=Z= dd"l>m?Z? dd#l@mAZA dd$lBmCZCmDZD dd%lEmFZFmGZG dd&lHmIZI dd'lJmKZK G d(d) d)e	ZLdS )*z-
Represents a connection to the EC2 service.
    N)datetime)	timedelta)detect_potential_sigv4)AWSQueryConnection)	ResultSet)ImageImageAttribute	CopyImage)ReservationInstance)ConsoleOutputInstanceAttribute)KeyPair)Address)VolumeVolumeAttribute)Snapshot)SnapshotAttribute)Zone)SecurityGroup)
RegionInfo)InstanceInfo)ReservedInstancesOffering)ReservedInstance)ReservedInstanceListing)ReservedInstancesConfiguration)ModifyReservedInstancesResult)ReservedInstancesModification)SpotInstanceRequest)SpotPriceHistory)SpotDatafeedSubscription)BundleInstanceTask)PlacementGroup)Tag)InstanceType)InstanceStatusSet)VolumeStatusSet)NetworkInterface)AccountAttributeVPCAttribute)BlockDeviceMappingBlockDeviceType)EC2ResponseError)sixc                       s\  e Zd ZejdddZejdddZejdddZe	Z
d fdd	Zdd Zdd Zdd ZdddZdddZdddZdddZdddZddd Zdd!d"Zd d$d%Zdd'd(Zdd)d*Zdd+d,Zdd-d.Zdd/d0Zdd1d2Zdd5d6Zdd7d8Zd	d9d:Zd
d;d<Z dd=d>Z!dd?d@Z"ddAdBZ#ddCdDZ$ddEdFZ%ddGdHZ&ddIdJZ'ddKdLZ(ddMdNZ)ddPdQZ*ddRdSZ+ddTdUZ,ddVdWZ-ddXdYZ.ddZd[Z/dd\d]Z0dd^d_Z1dd`daZ2ddbdcZ3ddddeZ4ddfdgZ5d dhdiZ6d!djdkZ7d"dldmZ8d#dndoZ9d$dpdqZ:d%drdsZ;d&dudvZ<d'dwdxZ=d(dydzZ>d)d{d|Z?d*d}d~Z@d+ddZAd,ddZBd-ddZCd.ddZDd/ddZEd0ddZFd1ddZGd2ddZHd3ddZId4ddZJd5ddZKd6ddZLd7ddZMd8ddZNd9ddZOd:ddZPd;ddZQd<ddZRd=ddZSd>ddZTd?ddZUd@ddZVdAddZWdBddZXdCddZYdDddZZdEddZ[dFddZ\dGddZ]dd Z^dd Z_dHddZ`dIddĄZadJddƄZbdKddȄZcdLddʄZddMdd̄ZedNdd΄ZfdOddЄZgdPdd҄ZhdQddԄZidRddׄZjdSddلZkddۄ ZldTdd݄ZmdUdd߄ZndVddZodWddZpdXddZqdYddZrdZddZsd[ddZtdd Zud\ddZvd]ddZwd^ddZxd_ddZyd`ddZz  Z{S (a  EC2ConnectionZBotoZec2_versionz
2014-10-01Zec2_region_namez	us-east-1Zec2_region_endpointzec2.us-east-1.amazonaws.comNTr   /c                    sZ   |st | | j| j}|| _tt| j||||||||	| jj|
|||||d |rV|| _dS )z@
        Init method to create a new connection to EC2.
        )validate_certsprofile_nameN)	r   DefaultRegionNameDefaultRegionEndpointregionsuperr.   __init__Zendpoint
APIVersion)selfaws_access_key_idaws_secret_access_key	is_securehostportproxy
proxy_port
proxy_user
proxy_passdebughttps_connection_factoryr4   pathapi_versionZsecurity_tokenr0   r1   	__class__ 7/tmp/pip-unpacked-wheel-dlxw5sjy/boto/ec2/connection.pyr6   Q   s.    
      	zEC2Connection.__init__c                 C   s   dgS )Nzhmac-v4rH   )r8   rH   rH   rI   _required_auth_capabilityk   s    z'EC2Connection._required_auth_capabilityc              
   C   s8   ddddddddd	d
g
}i }|D ]}t | |||< q |S )z
        Returns a dictionary containing the value of all of the keyword
        arguments passed when constructing this connection.
        r9   r:   r;   r=   r>   r?   r@   rA   rB   rC   )getattr)r8   Zparam_namesparamsnamerH   rH   rI   
get_paramsn   s         zEC2Connection.get_paramsc           	      C   s   t |tst|}d}|D ]p}|}|ds8|dd}||d| < || }t |ts\|g}d}|D ]}||d||f < |d7 }qd|d7 }qd S )N   ztag:_-zFilter.%d.NamezFilter.%d.Value.%d)
isinstancedict
startswithreplacelist)	r8   rL   filtersirM   Zaws_namevaluejvrH   rH   rI   build_filter_params|   s     



z!EC2Connection.build_filter_paramsFc                 C   sn   i }|r|  ||d |r(|  ||d |r:|  ||d |rJ| || |rVd|d< | jd|dtfgdd	S )
a  
        Retrieve all the EC2 images available on your account.

        :type image_ids: list
        :param image_ids: A list of strings with the image IDs wanted

        :type owners: list
        :param owners: A list of owner IDs, the special strings 'self',
            'amazon', and 'aws-marketplace', may be used to describe
            images owned by you, Amazon or AWS Marketplace
            respectively

        :type executable_by: list
        :param executable_by: Returns AMIs for which the specified
                              user ID has explicit launch permissions

        :type filters: dict
        :param filters: Optional filters that can be used to limit the
            results returned.  Filters are provided in the form of a
            dictionary consisting of filter names as the key and
            filter values as the value.  The set of allowable filter
            names/values is dependent on the request being performed.
            Check the EC2 API guide for details.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of :class:`boto.ec2.image.Image`
        ImageIdOwnerZExecutableBytrueDryRunDescribeImagesitemPOSTZverbbuild_list_paramsr\   get_listr   )r8   	image_idsownersZexecutable_byrW   dry_runrL   rH   rH   rI   get_all_images   s      zEC2Connection.get_all_imagesc                 C   s`   i }|r|  ||d |r(|  ||d ddi}| || |rHd|d< | jd|dtfgd	d
S )a  
        Retrieve all the EC2 kernels available on your account.
        Constructs a filter to allow the processing to happen server side.

        :type kernel_ids: list
        :param kernel_ids: A list of strings with the image IDs wanted

        :type owners: list
        :param owners: A list of owner IDs

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of :class:`boto.ec2.image.Image`
        r]   r^   
image-typekernelr_   r`   ra   rb   rc   rd   re   )r8   Z
kernel_idsri   rj   rL   filterrH   rH   rI   get_all_kernels   s     zEC2Connection.get_all_kernelsc                 C   s`   i }|r|  ||d |r(|  ||d ddi}| || |rHd|d< | jd|dtfgd	d
S )a  
        Retrieve all the EC2 ramdisks available on your account.
        Constructs a filter to allow the processing to happen server side.

        :type ramdisk_ids: list
        :param ramdisk_ids: A list of strings with the image IDs wanted

        :type owners: list
        :param owners: A list of owner IDs

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of :class:`boto.ec2.image.Image`
        r]   r^   rl   Zramdiskr_   r`   ra   rb   rc   rd   re   )r8   Zramdisk_idsri   rj   rL   rn   rH   rH   rI   get_all_ramdisks   s     zEC2Connection.get_all_ramdisksc                 C   s2   z| j |g|dd W S  tk
r,   Y dS X dS )a  
        Shortcut method to retrieve a specific image (AMI).

        :type image_id: string
        :param image_id: the ID of the Image to retrieve

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: :class:`boto.ec2.image.Image`
        :return: The EC2 Image specified or None if the image is not found
        )rh   rj   r   N)rk   
IndexError)r8   image_idrj   rH   rH   rI   	get_image   s    zEC2Connection.get_imagec                 C   s   i }|r||d< |r||d< |r(||d< |r4||d< |r@||d< |rL||d< |rX||d< |rvt ||d}t }|||< |r|| |	rd	|d
< |
r|
|d< |r||d< | jd|tdd}t|dd}|S )a?  
        Register an image.

        :type name: string
        :param name: The name of the AMI.  Valid only for EBS-based images.

        :type description: string
        :param description: The description of the AMI.

        :type image_location: string
        :param image_location: Full path to your AMI manifest in
            Amazon S3 storage.  Only used for S3-based AMI's.

        :type architecture: string
        :param architecture: The architecture of the AMI.  Valid choices are:
            * i386
            * x86_64

        :type kernel_id: string
        :param kernel_id: The ID of the kernel with which to launch
            the instances

        :type root_device_name: string
        :param root_device_name: The root device name (e.g. /dev/sdh)

        :type block_device_map: :class:`boto.ec2.blockdevicemapping.BlockDeviceMapping`
        :param block_device_map: A BlockDeviceMapping data structure
            describing the EBS volumes associated with the Image.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :type virtualization_type: string
        :param virtualization_type: The virutalization_type of the image.
            Valid choices are:
            * paravirtual
            * hvm

        :type sriov_net_support: string
        :param sriov_net_support: Advanced networking support.
            Valid choices are:
            * simple

        :type snapshot_id: string
        :param snapshot_id: A snapshot ID for the snapshot to be used
            as root device for the image. Mutually exclusive with
            block_device_map, requires root_device_name

        :type delete_root_volume_on_termination: bool
        :param delete_root_volume_on_termination: Whether to delete the root
            volume of the image after instance termination. Only applies when
            creating image from snapshot_id. Defaults to False.  Note that
            leaving volumes behind after instance termination is not free.

        :rtype: string
        :return: The new image id
        NameDescriptionZArchitectureKernelId	RamdiskIdZImageLocationZRootDeviceName)snapshot_idZdelete_on_terminationr_   r`   ZVirtualizationTypeZSriovNetSupportZRegisterImagerc   rd   ZimageIdN)r+   r*   ec2_build_list_params
get_objectr   rK   )r8   rM   descriptionZimage_locationarchitecture	kernel_id
ramdisk_idZroot_device_nameblock_device_maprj   Zvirtualization_typeZsriov_net_supportrx   Z!delete_root_volume_on_terminationrL   Zroot_volrsrr   rH   rH   rI   register_image  s@    @
zEC2Connection.register_imagec           	      C   st   d}|r6|  |}|jD ]}|dkr|j| j} q6qd|i}|rJd|d< | jd|dd}|rp|rp|on| |S |S )	a  
        Unregister an AMI.

        :type image_id: string
        :param image_id: the ID of the Image to unregister

        :type delete_snapshot: bool
        :param delete_snapshot: Set to True if we should delete the
            snapshot associated with an EBS volume mounted at /dev/sda1

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: True if successful
        Nz	/dev/sda1r]   r_   r`   ZDeregisterImagerc   rd   )rs   block_device_mappingrx   
get_statusdelete_snapshot)	r8   rr   r   rj   rx   imagekeyrL   resultrH   rH   rI   deregister_imagel  s&    

  zEC2Connection.deregister_imagec           	      C   sT   ||d}|r||d< |r"d|d< |r0| | |r<d|d< | jd|tdd}|jS )	a  
        Will create an AMI from the instance in the running or stopped
        state.

        :type instance_id: string
        :param instance_id: the ID of the instance to image.

        :type name: string
        :param name: The name of the new image

        :type description: string
        :param description: An optional human-readable string describing
            the contents and purpose of the AMI.

        :type no_reboot: bool
        :param no_reboot: An optional flag indicating that the
            bundling process should not attempt to shutdown the
            instance before bundling.  If this flag is True, the
            responsibility of maintaining file system integrity is
            left to the owner of the instance.

        :type block_device_mapping: :class:`boto.ec2.blockdevicemapping.BlockDeviceMapping`
        :param block_device_mapping: A BlockDeviceMapping data structure
            describing the EBS volumes associated with the Image.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: string
        :return: The new image id
        )
InstanceIdrt   ru   r_   ZNoRebootr`   ZCreateImagerc   rd   )ry   rz   r   id)	r8   instance_idrM   r{   Z	no_rebootr   rj   rL   imgrH   rH   rI   create_image  s    "
zEC2Connection.create_imagelaunchPermissionc                 C   s(   ||d}|rd|d< | j d|tddS )a  
        Gets an attribute from an image.

        :type image_id: string
        :param image_id: The Amazon image id for which you want info about

        :type attribute: string
        :param attribute: The attribute you need information about.
            Valid choices are:
            * launchPermission
            * productCodes
            * blockDeviceMapping

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: :class:`boto.ec2.image.ImageAttribute`
        :return: An ImageAttribute object representing the value of the
                 attribute requested
        r]   	Attributer_   r`   ZDescribeImageAttributerc   rd   )rz   r   r8   rr   	attributerj   rL   rH   rH   rI   get_image_attribute  s     z!EC2Connection.get_image_attributeaddc           	      C   s^   |||d}|r|  ||d |r0|  ||d |rB|  ||d |rNd|d< | jd|dd	S )
a  
        Changes an attribute of an image.

        :type image_id: string
        :param image_id: The image id you wish to change

        :type attribute: string
        :param attribute: The attribute you wish to change

        :type operation: string
        :param operation: Either add or remove (this is required for changing
            launchPermissions)

        :type user_ids: list
        :param user_ids: The Amazon IDs of users to add/remove attributes

        :type groups: list
        :param groups: The groups to add/remove attributes

        :type product_codes: list
        :param product_codes: Amazon DevPay product code. Currently only one
            product code can be associated with an AMI. Once
            set, the product code cannot be changed or reset.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        )r]   r   OperationTypeUserId	UserGroupProductCoder_   r`   ZModifyImageAttributerc   rd   rf   r   )	r8   rr   r   	operationuser_idsgroupsZproduct_codesrj   rL   rH   rH   rI   modify_image_attribute  s    z$EC2Connection.modify_image_attributec                 C   s&   ||d}|rd|d< | j d|ddS )a  
        Resets an attribute of an AMI to its default value.

        :type image_id: string
        :param image_id: ID of the AMI for which an attribute will be described

        :type attribute: string
        :param attribute: The attribute to reset

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: Whether the operation succeeded or not
        r   r_   r`   ZResetImageAttributerc   rd   r   r   rH   rH   rI   reset_image_attribute	  s    z#EC2Connection.reset_image_attributec                 C   s   t dt | j||||dS )a  
        Retrieve all the instance reservations associated with your account.

        .. note::
        This method's current behavior is deprecated in favor of
        :meth:`get_all_reservations`.  A future major release will change
        :meth:`get_all_instances` to return a list of
        :class:`boto.ec2.instance.Instance` objects as its name suggests.
        To obtain that behavior today, use :meth:`get_only_instances`.

        :type instance_ids: list
        :param instance_ids: A list of strings of instance IDs

        :type filters: dict
        :param filters: Optional filters that can be used to limit the
            results returned.  Filters are provided in the form of a
            dictionary consisting of filter names as the key and
            filter values as the value.  The set of allowable filter
            names/values is dependent on the request being performed.
            Check the EC2 API guide for details.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :type max_results: int
        :param max_results: The maximum number of paginated instance
            items per response.

        :rtype: list
        :return: A list of  :class:`boto.ec2.instance.Reservation`

        zXThe current get_all_instances implementation will be replaced with get_all_reservations.)instance_idsrW   rj   max_results)warningswarnPendingDeprecationWarningget_all_reservations)r8   r   rW   rj   r   rH   rH   rI   get_all_instances"  s    " zEC2Connection.get_all_instancesc                 C   sB   d}g }| j |||||d}|dd |D  |j}|sq>q|S )a  
        Retrieve all the instances associated with your account.

        :type instance_ids: list
        :param instance_ids: A list of strings of instance IDs

        :type filters: dict
        :param filters: Optional filters that can be used to limit the
            results returned.  Filters are provided in the form of a
            dictionary consisting of filter names as the key and
            filter values as the value.  The set of allowable filter
            names/values is dependent on the request being performed.
            Check the EC2 API guide for details.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :type max_results: int
        :param max_results: The maximum number of paginated instance
            items per response.

        :rtype: list
        :return: A list of  :class:`boto.ec2.instance.Instance`
        N)r   rW   rj   r   
next_tokenc                 S   s   g | ]}|j D ]}|qqS rH   )Z	instances).0ZreservationinstancerH   rH   rI   
<listcomp>o  s     z4EC2Connection.get_only_instances.<locals>.<listcomp>)r   extendr   )r8   r   rW   rj   r   r   retvalZreservationsrH   rH   rI   get_only_instancesK  s    z EC2Connection.get_only_instancesc                 C   s   i }|r|  ||d |rZd|krN|d}|drBt|dkrNtdt | || |rfd|d< |dk	rv||d	< |r||d
< | jd|dt	fgddS )a-  
        Retrieve all the instance reservations associated with your account.

        :type instance_ids: list
        :param instance_ids: A list of strings of instance IDs

        :type filters: dict
        :param filters: Optional filters that can be used to limit the
            results returned.  Filters are provided in the form of a
            dictionary consisting of filter names as the key and
            filter values as the value.  The set of allowable filter
            names/values is dependent on the request being performed.
            Check the EC2 API guide for details.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :type max_results: int
        :param max_results: The maximum number of paginated instance
            items per response.

        :type next_token: str
        :param next_token: A string specifying the next paginated set
            of results to return.

        :rtype: list
        :return: A list of  :class:`boto.ec2.instance.Reservation`
        r   zgroup-idsg-   zThe group-id filter now requires a security group identifier (sg-*) instead of a group name. To filter by group name use the 'group-name' filter instead.r_   r`   N
MaxResults	NextTokenZDescribeInstancesrb   rc   rd   )
rf   getrT   lenr   r   UserWarningr\   rg   r
   )r8   r   rW   rj   r   r   rL   gidrH   rH   rI   r   w  s,    
 z"EC2Connection.get_all_reservationsc                 C   sh   i }|r|  ||d |r"||d< |r.||d< |r>| || |rJd|d< |rVd|d< | jd|tdd	S )
a  
        Retrieve all the instances in your account scheduled for maintenance.

        :type instance_ids: list
        :param instance_ids: A list of strings of instance IDs

        :type max_results: int
        :param max_results: The maximum number of paginated instance
            items per response.

        :type next_token: str
        :param next_token: A string specifying the next paginated set
            of results to return.

        :type filters: dict
        :param filters: Optional filters that can be used to limit
            the results returned.  Filters are provided
            in the form of a dictionary consisting of
            filter names as the key and filter values
            as the value.  The set of allowable filter
            names/values is dependent on the request
            being performed.  Check the EC2 API guide
            for details.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :type include_all_instances: bool
        :param include_all_instances: Set to True if all
            instances should be returned. (Only running
            instances are included by default.)

        :rtype: list
        :return: A list of instances that have maintenance scheduled.
        r   r   r   r_   r`   ZIncludeAllInstancesZDescribeInstanceStatusrc   rd   )rf   r\   rz   r%   )r8   r   r   r   rW   rj   Zinclude_all_instancesrL   rH   rH   rI   get_all_instance_status  s"    ' z%EC2Connection.get_all_instance_statusrO   m1.smallc                  C   s  |||d}|r||d< |rZg }|D ]&}t |tr@||j q$|| q$| ||d |rg }|D ]&}t |tr||j qf|| qf| ||d |rt |tjr|d}t	
|d|d< |r||d< |r||d< |	r|	|d	< |r||d
< |r||d< |
r|
|d< |r$||d< |r2d|d< |r@||d< |rN||d< |r^|| |rld|d< |r~|}||d< |r||d< |r||d< |r||d< |r||d< |rd|d< |r|| |rd|d< | jd|tddS )a  
        Runs an image on EC2.

        :type image_id: string
        :param image_id: The ID of the image to run.

        :type min_count: int
        :param min_count: The minimum number of instances to launch.

        :type max_count: int
        :param max_count: The maximum number of instances to launch.

        :type key_name: string
        :param key_name: The name of the key pair with which to
            launch instances.

        :type security_groups: list of strings
        :param security_groups: The names of the EC2 classic security groups
            with which to associate instances

        :type user_data: string
        :param user_data: The user data passed to the launched instances

        :type instance_type: string
        :param instance_type: The type of instance to run:

            * t1.micro
            * m1.small
            * m1.medium
            * m1.large
            * m1.xlarge
            * m3.medium
            * m3.large
            * m3.xlarge
            * m3.2xlarge
            * c1.medium
            * c1.xlarge
            * m2.xlarge
            * m2.2xlarge
            * m2.4xlarge
            * cr1.8xlarge
            * hi1.4xlarge
            * hs1.8xlarge
            * cc1.4xlarge
            * cg1.4xlarge
            * cc2.8xlarge
            * g2.2xlarge
            * c3.large
            * c3.xlarge
            * c3.2xlarge
            * c3.4xlarge
            * c3.8xlarge
            * c4.large
            * c4.xlarge
            * c4.2xlarge
            * c4.4xlarge
            * c4.8xlarge
            * i2.xlarge
            * i2.2xlarge
            * i2.4xlarge
            * i2.8xlarge
            * t2.micro
            * t2.small
            * t2.medium

        :type placement: string
        :param placement: The Availability Zone to launch the instance into.

        :type kernel_id: string
        :param kernel_id: The ID of the kernel with which to launch the
            instances.

        :type ramdisk_id: string
        :param ramdisk_id: The ID of the RAM disk with which to launch the
            instances.

        :type monitoring_enabled: bool
        :param monitoring_enabled: Enable detailed CloudWatch monitoring on
            the instance.

        :type subnet_id: string
        :param subnet_id: The subnet ID within which to launch the instances
            for VPC.

        :type private_ip_address: string
        :param private_ip_address: If you're using VPC, you can
            optionally use this parameter to assign the instance a
            specific available IP address from the subnet (e.g.,
            10.0.0.25).

        :type block_device_map: :class:`boto.ec2.blockdevicemapping.BlockDeviceMapping`
        :param block_device_map: A BlockDeviceMapping data structure
            describing the EBS volumes associated with the Image.

        :type disable_api_termination: bool
        :param disable_api_termination: If True, the instances will be locked
            and will not be able to be terminated via the API.

        :type instance_initiated_shutdown_behavior: string
        :param instance_initiated_shutdown_behavior: Specifies whether the
            instance stops or terminates on instance-initiated shutdown.
            Valid values are:

            * stop
            * terminate

        :type placement_group: string
        :param placement_group: If specified, this is the name of the placement
            group in which the instance(s) will be launched.

        :type client_token: string
        :param client_token: Unique, case-sensitive identifier you provide
            to ensure idempotency of the request. Maximum 64 ASCII characters.

        :type security_group_ids: list of strings
        :param security_group_ids: The ID of the VPC security groups with
            which to associate instances.

        :type additional_info: string
        :param additional_info: Specifies additional information to make
            available to the instance(s).

        :type tenancy: string
        :param tenancy: The tenancy of the instance you want to
            launch. An instance with a tenancy of 'dedicated' runs on
            single-tenant hardware and can only be launched into a
            VPC. Valid values are:"default" or "dedicated".
            NOTE: To use dedicated tenancy you MUST specify a VPC
            subnet-ID as well.

        :type instance_profile_arn: string
        :param instance_profile_arn: The Amazon resource name (ARN) of
            the IAM Instance Profile (IIP) to associate with the instances.

        :type instance_profile_name: string
        :param instance_profile_name: The name of
            the IAM Instance Profile (IIP) to associate with the instances.

        :type ebs_optimized: bool
        :param ebs_optimized: Whether the instance is optimized for
            EBS I/O.  This optimization provides dedicated throughput
            to Amazon EBS and an optimized configuration stack to
            provide optimal EBS I/O performance.  This optimization
            isn't available with all instance types.

        :type network_interfaces: :class:`boto.ec2.networkinterface.NetworkInterfaceCollection`
        :param network_interfaces: A NetworkInterfaceCollection data
            structure containing the ENI specifications for the instance.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: Reservation
        :return: The :class:`boto.ec2.instance.Reservation` associated with
                 the request for machines
        )r]   ZMinCountZMaxCountKeyNameSecurityGroupIdr   zutf-8ZUserDataZAddressingTyper$   zPlacement.AvailabilityZonezPlacement.GroupNamezPlacement.Tenancyrv   rw   r_   zMonitoring.EnabledSubnetIdPrivateIpAddressZDisableApiTerminationZ!InstanceInitiatedShutdownBehaviorClientTokenZAdditionalInfozIamInstanceProfile.NamezIamInstanceProfile.ArnZEbsOptimizedr`   ZRunInstancesrc   rd   )rR   r   appendr   rf   rM   r-   	text_typeencodebase64	b64encodedecodery   rz   r
   ) r8   rr   Z	min_count	max_countkey_namesecurity_groups	user_dataaddressing_typeinstance_type	placementr}   r~   monitoring_enabled	subnet_idr   Zdisable_api_terminationZ$instance_initiated_shutdown_behaviorprivate_ip_addressplacement_groupclient_tokensecurity_group_idsZadditional_infoinstance_profile_nameinstance_profile_arnZtenancyebs_optimizednetwork_interfacesrj   rL   lgroupvalrH   rH   rI   run_instances  s     -





zEC2Connection.run_instancesc                 C   s:   i }|r|  ||d |r"d|d< | jd|dtfgddS )aZ  
        Terminate the instances specified

        :type instance_ids: list
        :param instance_ids: A list of strings of the Instance IDs to terminate

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of the instances terminated
        r   r_   r`   ZTerminateInstancesrb   rc   rd   rf   rg   r   r8   r   rj   rL   rH   rH   rI   terminate_instances  s     z!EC2Connection.terminate_instancesc                 C   sF   i }|rd|d< |r"|  ||d |r.d|d< | jd|dtfgddS )	a  
        Stop the instances specified

        :type instance_ids: list
        :param instance_ids: A list of strings of the Instance IDs to stop

        :type force: bool
        :param force: Forces the instance to stop

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of the instances stopped
        r_   Forcer   r`   ZStopInstancesrb   rc   rd   r   )r8   r   forcerj   rL   rH   rH   rI   stop_instances  s     zEC2Connection.stop_instancesc                 C   s:   i }|r|  ||d |r"d|d< | jd|dtfgddS )aO  
        Start the instances specified

        :type instance_ids: list
        :param instance_ids: A list of strings of the Instance IDs to start

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of the instances started
        r   r_   r`   ZStartInstancesrb   rc   rd   r   r   rH   rH   rI   start_instances  s     zEC2Connection.start_instancesc                 C   s2   i }|  ||gd |r d|d< | jd|tddS )a  
        Retrieves the console output for the specified instance.

        :type instance_id: string
        :param instance_id: The instance ID of a running instance on the cloud.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: :class:`boto.ec2.instance.ConsoleOutput`
        :return: The console output as a ConsoleOutput object
        r   r_   r`   ZGetConsoleOutputrc   rd   )rf   rz   r   )r8   r   rj   rL   rH   rH   rI   get_console_output  s     z EC2Connection.get_console_outputc                 C   s.   i }|r|  ||d |r"d|d< | d|S )a  
        Reboot the specified instances.

        :type instance_ids: list
        :param instance_ids: The instances to terminate and reboot

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        r   r_   r`   ZRebootInstancesr   r   rH   rH   rI   reboot_instances+  s    zEC2Connection.reboot_instancesc                 C   s4   ||d}|rd|d< | j d|tdd}|j|jfS )t
        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        )r   r   r_   r`   ZConfirmProductInstancerc   rd   )rz   r   statusZownerId)r8   Zproduct_coder   rj   rL   r   rH   rH   rI   confirm_product_instance=  s     z&EC2Connection.confirm_product_instancec                 C   s2   d|i}|r||d< |r d|d< | j d|tddS )a  
        Gets an attribute from an instance.

        :type instance_id: string
        :param instance_id: The Amazon id of the instance

        :type attribute: string
        :param attribute: The attribute you need information about
            Valid choices are:

            * instanceType
            * kernel
            * ramdisk
            * userData
            * disableApiTermination
            * instanceInitiatedShutdownBehavior
            * rootDeviceName
            * blockDeviceMapping
            * productCodes
            * sourceDestCheck
            * groupSet
            * ebsOptimized
            * sriovNetSupport

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: :class:`boto.ec2.image.InstanceAttribute`
        :return: An InstanceAttribute object representing the value of the
                 attribute requested
        r   r   r_   r`   ZDescribeInstanceAttributerc   rd   )rz   r   r8   r   r   rj   rL   rH   rH   rI   get_instance_attributeN  s      z$EC2Connection.get_instance_attributec           
      C   s  d}|  |kr>t|tr*|r$d}q>d}n|dkr>td| d|i}|  dkrt|D ](\}}	t|	trr|	j}	|	|d|d	  < qZnd|  d
kr||d< nN|  dkr||d< n8|  dkr||d< |std||d< ntd|f |rd|d< | jd|ddS )a3  
        Changes an attribute of a network interface.

        :type interface_id: string
        :param interface_id: The interface id. Looks like 'eni-xxxxxxxx'

        :type attr: string
        :param attr: The attribute you wish to change.

            Learn more at http://docs.aws.amazon.com/AWSEC2/latest/API            Reference/ApiReference-query-ModifyNetworkInterfaceAttribute.html

            * description - Textual description of interface
            * groupSet - List of security group ids or group objects
            * sourceDestCheck - Boolean
            * deleteOnTermination - Boolean. Must also specify attachment_id

        :type value: string
        :param value: The new value for the attribute

        :rtype: bool
        :return: Whether the operation succeeded or not

        :type attachment_id: string
        :param attachment_id: If you're modifying DeleteOnTermination you must
            specify the attachment_id.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        )deleteonterminationsourcedestcheckr_   false)r_   r   z)%s must be a boolean, "true", or "false"!NetworkInterfaceIdgroupsetzSecurityGroupId.%srO   r{   zDescription.Valuer   zSourceDestCheck.Valuer   zAttachment.DeleteOnTerminationz&You must also specify an attachment_idzAttachment.AttachmentIdzUnknown attribute "%s"r`   ZModifyNetworkInterfaceAttributerc   rd   )lowerrR   bool
ValueError	enumerater   r   r   )
r8   Zinterface_idattrrY   attachment_idrj   	bool_reqsrL   idxsgrH   rH   rI   "modify_network_interface_attributev  sB    !




  z0EC2Connection.modify_network_interface_attributec                 C   s  d}|  |kr(t|tr(|r$d}nd}d|i}|  dkrpt|D ](\}}t|tr\|j}||d|d  < qDn||  dkrt|D ]@\}}	|	d	\}
}}d
|d  }|
|d| < |pd|d| < qn$|d  |dd  }||d| < |rd|d< | jd|ddS )aR  
        Changes an attribute of an instance

        :type instance_id: string
        :param instance_id: The instance id you wish to change

        :type attribute: string
        :param attribute: The attribute you wish to change.

            * instanceType - A valid instance type (m1.small)
            * kernel - Kernel ID (None)
            * ramdisk - Ramdisk ID (None)
            * userData - Base64 encoded String (None)
            * disableApiTermination - Boolean (true)
            * instanceInitiatedShutdownBehavior - stop|terminate
            * blockDeviceMapping - List of strings - ie: ['/dev/sda=false']
            * sourceDestCheck - Boolean (true)
            * groupSet - Set of Security Groups or IDs
            * ebsOptimized - Boolean (false)
            * sriovNetSupport - String - ie: 'simple'

        :type value: string
        :param value: The new value for the attribute

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: Whether the operation succeeded or not
        )Zdisableapiterminationr   Zebsoptimizedr_   r   r   r   z
GroupId.%srO   Zblockdevicemapping=zBlockDeviceMapping.%dz%s.DeviceNamez%s.Ebs.DeleteOnTerminationr   Nz%s.Valuer`   ZModifyInstanceAttributerc   rd   )	r   rR   r   r   r   r   	partitionupperr   )r8   r   r   rY   rj   r   rL   r   r   kvZdev_namerP   flagprerH   rH   rI   modify_instance_attribute  s.    !

z'EC2Connection.modify_instance_attributec                 C   s&   ||d}|rd|d< | j d|ddS )a  
        Resets an attribute of an instance to its default value.

        :type instance_id: string
        :param instance_id: ID of the instance

        :type attribute: string
        :param attribute: The attribute to reset. Valid values are:
                          kernel|ramdisk

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: Whether the operation succeeded or not
        )r   r   r_   r`   ZResetInstanceAttributerc   rd   r   r   rH   rH   rI   reset_instance_attribute   s    z&EC2Connection.reset_instance_attributec                 C   s~   i }|r|  ||d |rZd|krN|d}|drBt|dkrNtdt | || |rfd|d< | jd|d	t	fgd
dS )aQ  
        Retrieve all the spot instances requests associated with your account.

        :type request_ids: list
        :param request_ids: A list of strings of spot instance request IDs

        :type filters: dict
        :param filters: Optional filters that can be used to limit the
            results returned.  Filters are provided in the form of a
            dictionary consisting of filter names as the key and
            filter values as the value.  The set of allowable filter
            names/values is dependent on the request being performed.
            Check the EC2 API guide for details.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of
                 :class:`boto.ec2.spotinstancerequest.SpotInstanceRequest`
        SpotInstanceRequestIdzlaunch.group-idr   r   zThe 'launch.group-id' filter now requires a security group id (sg-*) and no longer supports filtering by group name. Please update your filters accordingly.r_   r`   ZDescribeSpotInstanceRequestsrb   rc   rd   )
rf   r   rT   r   r   r   r   r\   rg   r   )r8   request_idsrW   rj   rL   ZlgidrH   rH   rI   get_all_spot_instance_requests  s$    
 z,EC2Connection.get_all_spot_instance_requestsc
                 C   s   i }
|r||
d< |r||
d< |r(||
d< |r4||
d< |r@||
d< |rLd|
d< |dk	r\||
d	< |rh||
d
< |	rx|  |
|	 | jd|
dtfgddS )a  
        Retrieve the recent history of spot instances pricing.

        :type start_time: str
        :param start_time: An indication of how far back to provide price
            changes for. An ISO8601 DateTime string.

        :type end_time: str
        :param end_time: An indication of how far forward to provide price
            changes for.  An ISO8601 DateTime string.

        :type instance_type: str
        :param instance_type: Filter responses to a particular instance type.

        :type product_description: str
        :param product_description: Filter responses to a particular platform.
            Valid values are currently:

            * Linux/UNIX
            * SUSE Linux
            * Windows
            * Linux/UNIX (Amazon VPC)
            * SUSE Linux (Amazon VPC)
            * Windows (Amazon VPC)

        :type availability_zone: str
        :param availability_zone: The availability zone for which prices
            should be returned.  If not specified, data for all
            availability zones will be returned.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :type max_results: int
        :param max_results: The maximum number of paginated items
            per response.

        :type next_token: str
        :param next_token: The next set of rows to return.  This should
            be the value of the ``next_token`` attribute from a previous
            call to ``get_spot_price_history``.

        :type filters: dict
        :param filters: Optional filters that can be used to limit the
            results returned.  Filters are provided in the form of a
            dictionary consisting of filter names as the key and
            filter values as the value.  The set of allowable filter
            names/values is dependent on the request being performed.
            Check the EC2 API guide for details.

        :rtype: list
        :return: A list tuples containing price and timestamp.
        Z	StartTimeZEndTimer$   ProductDescriptionAvailabilityZoner_   r`   Nr   r   ZDescribeSpotPriceHistoryrb   rc   rd   )r\   rg   r   )r8   
start_timeZend_timer   product_descriptionavailability_zonerj   r   r   rW   rL   rH   rH   rI   get_spot_price_historyB  s.    : z$EC2Connection.get_spot_price_historyone-timec                 C   s"  d}d| |d|d|i}|r$||d< |r0||d< |r<||d< |rH||d< |rT||d	< |	rd|	|d
| < |rg }|D ]&}t |tr||j qp|| qp| ||d|  |
rg }|
D ]&}t |tr||j q|| q| ||d|  |rt||d| < |r||d| < |r,||d| < |r>||d| < |rP||d| < |rb||d| < |rtd|d| < |r||d| < |r||d| < |r||d|  |r||d| < |r||d| < |rd|d| < |r|j||d d |r
d|d< | j	d|dt
fgd d!S )"a  
        Request instances on the spot market at a particular price.

        :type price: str
        :param price: The maximum price of your bid

        :type image_id: string
        :param image_id: The ID of the image to run

        :type count: int
        :param count: The of instances to requested

        :type type: str
        :param type: Type of request. Can be 'one-time' or 'persistent'.
                     Default is one-time.

        :type valid_from: str
        :param valid_from: Start date of the request. An ISO8601 time string.

        :type valid_until: str
        :param valid_until: End date of the request.  An ISO8601 time string.

        :type launch_group: str
        :param launch_group: If supplied, all requests will be fulfilled
            as a group.

        :type availability_zone_group: str
        :param availability_zone_group: If supplied, all requests will be
            fulfilled within a single availability zone.

        :type key_name: string
        :param key_name: The name of the key pair with which to
            launch instances

        :type security_groups: list of strings
        :param security_groups: The names of the security groups with which to
            associate instances

        :type user_data: string
        :param user_data: The user data passed to the launched instances

        :type instance_type: string
        :param instance_type: The type of instance to run:

            * t1.micro
            * m1.small
            * m1.medium
            * m1.large
            * m1.xlarge
            * m3.medium
            * m3.large
            * m3.xlarge
            * m3.2xlarge
            * c1.medium
            * c1.xlarge
            * m2.xlarge
            * m2.2xlarge
            * m2.4xlarge
            * cr1.8xlarge
            * hi1.4xlarge
            * hs1.8xlarge
            * cc1.4xlarge
            * cg1.4xlarge
            * cc2.8xlarge
            * g2.2xlarge
            * c3.large
            * c3.xlarge
            * c3.2xlarge
            * c3.4xlarge
            * c3.8xlarge
            * c4.large
            * c4.xlarge
            * c4.2xlarge
            * c4.4xlarge
            * c4.8xlarge
            * i2.xlarge
            * i2.2xlarge
            * i2.4xlarge
            * i2.8xlarge
            * t2.micro
            * t2.small
            * t2.medium

        :type placement: string
        :param placement: The availability zone in which to launch
            the instances

        :type kernel_id: string
        :param kernel_id: The ID of the kernel with which to launch the
            instances

        :type ramdisk_id: string
        :param ramdisk_id: The ID of the RAM disk with which to launch the
            instances

        :type monitoring_enabled: bool
        :param monitoring_enabled: Enable detailed CloudWatch monitoring on
            the instance.

        :type subnet_id: string
        :param subnet_id: The subnet ID within which to launch the instances
            for VPC.

        :type placement_group: string
        :param placement_group: If specified, this is the name of the placement
            group in which the instance(s) will be launched.

        :type block_device_map: :class:`boto.ec2.blockdevicemapping.BlockDeviceMapping`
        :param block_device_map: A BlockDeviceMapping data structure
            describing the EBS volumes associated with the Image.

        :type security_group_ids: list of strings
        :param security_group_ids: The ID of the VPC security groups with
            which to associate instances.

        :type instance_profile_arn: string
        :param instance_profile_arn: The Amazon resource name (ARN) of
            the IAM Instance Profile (IIP) to associate with the instances.

        :type instance_profile_name: string
        :param instance_profile_name: The name of
            the IAM Instance Profile (IIP) to associate with the instances.

        :type ebs_optimized: bool
        :param ebs_optimized: Whether the instance is optimized for
            EBS I/O.  This optimization provides dedicated throughput
            to Amazon EBS and an optimized configuration stack to
            provide optimal EBS I/O performance.  This optimization
            isn't available with all instance types.

        :type network_interfaces: list
        :param network_interfaces: A list of
            :class:`boto.ec2.networkinterface.NetworkInterfaceSpecification`

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: Reservation
        :return: The :class:`boto.ec2.spotinstancerequest.SpotInstanceRequest`
                 associated with the request for machines
        ZLaunchSpecificationz
%s.ImageIdTypeZ	SpotPriceInstanceCountZ	ValidFromZ
ValidUntilZLaunchGroupZAvailabilityZoneGroupz
%s.KeyNamez%s.SecurityGroupIdz%s.SecurityGroupz%s.UserDataz%s.AddressingTypez%s.InstanceTypez%s.Placement.AvailabilityZonez%s.KernelIdz%s.RamdiskIdr_   z%s.Monitoring.Enabledz%s.SubnetIdz%s.Placement.GroupNamez%s.z%s.IamInstanceProfile.Namez%s.IamInstanceProfile.Arnz%s.EbsOptimized.)prefixr`   ZRequestSpotInstancesrb   rc   rd   )rR   r   r   r   rf   rM   r   r   ry   rg   r   )r8   pricerr   counttypeZ
valid_fromZvalid_untilZlaunch_groupZavailability_zone_groupr   r   r   r   r   r   r}   r~   r   r   r   r   r   r   r   r   r   rj   ZlsrL   r   r   rH   rH   rI   request_spot_instances  s       

z$EC2Connection.request_spot_instancesc                 C   s:   i }|r|  ||d |r"d|d< | jd|dtfgddS )ab  
        Cancel the specified Spot Instance Requests.

        :type request_ids: list
        :param request_ids: A list of strings of the Request IDs to terminate

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of the instances terminated
        r   r_   r`   ZCancelSpotInstanceRequestsrb   rc   rd   )rf   rg   r   )r8   r   rj   rL   rH   rH   rI   cancel_spot_instance_requestsq  s     z+EC2Connection.cancel_spot_instance_requestsc                 C   s"   i }|rd|d< | j d|tddS )aq  
        Return the current spot instance data feed subscription
        associated with this account, if any.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: :class:`boto.ec2.spotdatafeedsubscription.SpotDatafeedSubscription`
        :return: The datafeed subscription object or None
        r_   r`   Z DescribeSpotDatafeedSubscriptionrc   rd   rz   r    r8   rj   rL   rH   rH   rI   get_spot_datafeed_subscription  s      z,EC2Connection.get_spot_datafeed_subscriptionc                 C   s2   d|i}|r||d< |r d|d< | j d|tddS )a  
        Create a spot instance datafeed subscription for this account.

        :type bucket: str or unicode
        :param bucket: The name of the bucket where spot instance data
                       will be written.  The account issuing this request
                       must have FULL_CONTROL access to the bucket
                       specified in the request.

        :type prefix: str or unicode
        :param prefix: An optional prefix that will be pre-pended to all
                       data files written to the bucket.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: :class:`boto.ec2.spotdatafeedsubscription.SpotDatafeedSubscription`
        :return: The datafeed subscription object or None
        ZBucketZPrefixr_   r`   ZCreateSpotDatafeedSubscriptionrc   rd   r  )r8   Zbucketr
  rj   rL   rH   rH   rI   !create_spot_datafeed_subscription  s      z/EC2Connection.create_spot_datafeed_subscriptionc                 C   s    i }|rd|d< | j d|ddS )a  
        Delete the current spot instance data feed subscription
        associated with this account

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: True if successful
        r_   r`   ZDeleteSpotDatafeedSubscriptionrc   rd   r   r  rH   rH   rI   !delete_spot_datafeed_subscription  s     z/EC2Connection.delete_spot_datafeed_subscriptionc                 C   sJ   i }|r|  ||d |r&| || |r2d|d< | jd|dtfgddS )a   
        Get all Availability Zones associated with the current region.

        :type zones: list
        :param zones: Optional list of zones.  If this list is present,
                      only the Zones associated with these zone names
                      will be returned.

        :type filters: dict
        :param filters: Optional filters that can be used to limit
                        the results returned.  Filters are provided
                        in the form of a dictionary consisting of
                        filter names as the key and filter values
                        as the value.  The set of allowable filter
                        names/values is dependent on the request
                        being performed.  Check the EC2 API guide
                        for details.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list of :class:`boto.ec2.zone.Zone`
        :return: The requested Zone objects
        ZZoneNamer_   r`   ZDescribeAvailabilityZonesrb   rc   rd   )rf   r\   rg   r   )r8   ZzonesrW   rj   rL   rH   rH   rI   get_all_zones  s     zEC2Connection.get_all_zonesc                 C   s\   i }|r|  ||d |r(|  ||d |r8| || |rDd|d< | jd|dtfgddS )	a  
        Get all EIP's associated with the current credentials.

        :type addresses: list
        :param addresses: Optional list of addresses.  If this list is present,
                           only the Addresses associated with these addresses
                           will be returned.

        :type filters: dict
        :param filters: Optional filters that can be used to limit
                        the results returned.  Filters are provided
                        in the form of a dictionary consisting of
                        filter names as the key and filter values
                        as the value.  The set of allowable filter
                        names/values is dependent on the request
                        being performed.  Check the EC2 API guide
                        for details.

        :type allocation_ids: list
        :param allocation_ids: Optional list of allocation IDs.  If this list is
                           present, only the Addresses associated with the given
                           allocation IDs will be returned.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list of :class:`boto.ec2.address.Address`
        :return: The requested Address objects
        PublicIpAllocationIdr_   r`   ZDescribeAddressesrb   rc   rd   )rf   r\   rg   r   )r8   	addressesrW   Zallocation_idsrj   rL   rH   rH   rI   get_all_addresses  s    zEC2Connection.get_all_addressesc                 C   s2   i }|dk	r||d< |r d|d< | j d|tddS )a  
        Allocate a new Elastic IP address and associate it with your account.

        :type domain: string
        :param domain: Optional string. If domain is set to "vpc" the address
            will be allocated to VPC . Will return address object with
            allocation_id.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: :class:`boto.ec2.address.Address`
        :return: The newly allocated Address
        NDomainr_   r`   ZAllocateAddressrc   rd   )rz   r   )r8   domainrj   rL   rH   rH   rI   allocate_address  s    zEC2Connection.allocate_addressc                 C   sd   i }|dk	r||d< |dk	r,|  ||d n|dk	r<||d< |rHd|d< |rTd|d< | jd|d	d
S )a  
        Assigns one or more secondary private IP addresses to a network
        interface in Amazon VPC.

        :type network_interface_id: string
        :param network_interface_id: The network interface to which the IP
            address will be assigned.

        :type private_ip_addresses: list
        :param private_ip_addresses: Assigns the specified IP addresses as
            secondary IP addresses to the network interface.

        :type secondary_private_ip_address_count: int
        :param secondary_private_ip_address_count: The number of secondary IP
            addresses to assign to the network interface. You cannot specify
            this parameter when also specifying private_ip_addresses.

        :type allow_reassignment: bool
        :param allow_reassignment: Specifies whether to allow an IP address
            that is already assigned to another network interface or instance
            to be reassigned to the specified network interface.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: True if successful
        Nr   r   ZSecondaryPrivateIpAddressCountr_   ZAllowReassignmentr`   ZAssignPrivateIpAddressesrc   rd   r   )r8   network_interface_idprivate_ip_addressesZ"secondary_private_ip_address_countZallow_reassignmentrj   rL   rH   rH   rI   assign_private_ip_addresses.  s     z)EC2Connection.assign_private_ip_addressesc	           
      C   s   i }	|d k	r||	d< n|d k	r&||	d< |d k	r8||	d< n|d k	rH||	d< |d k	rX||	d< |rdd|	d< |rpd|	d< |r| j d	|	d
dS | jd	|	td
dS d S )Nr   r   r  r  r   r_   ZAllowReassociationr`   ZAssociateAddressrc   rd   )r   rz   r   )
r8   r   r   	public_ipallocation_idr  r   allow_reassociationrj   rL   rH   rH   rI   _associate_addressb  s(    


z EC2Connection._associate_addressc              
   C   s   | j d|||||||dS )a  
        Associate an Elastic IP address with a currently running instance.
        This requires one of ``public_ip`` or ``allocation_id`` depending
        on if you're associating a VPC address or a plain EC2 address.

        When using an Allocation ID, make sure to pass ``None`` for ``public_ip``
        as EC2 expects a single parameter and if ``public_ip`` is passed boto
        will preference that instead of ``allocation_id``.

        :type instance_id: string
        :param instance_id: The ID of the instance

        :type public_ip: string
        :param public_ip: The public IP address for EC2 based allocations.

        :type allocation_id: string
        :param allocation_id: The allocation ID for a VPC-based elastic IP.

        :type network_interface_id: string
        :param network_interface_id: The network interface ID to which
            elastic IP is to be assigned to

        :type private_ip_address: string
        :param private_ip_address: The primary or secondary private IP address
            to associate with the Elastic IP address.

        :type allow_reassociation: bool
        :param allow_reassociation: Specify this option to allow an Elastic IP
            address that is already associated with another network interface
            or instance to be re-associated with the specified instance or
            interface.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: True if successful
        Tr   r   r!  r  r   r"  rj   r#  r8   r   r   r!  r  r   r"  rj   rH   rH   rI   associate_address  s    *  zEC2Connection.associate_addressc              
   C   s   | j d|||||||dS )a8  
        Associate an Elastic IP address with a currently running instance.
        This requires one of ``public_ip`` or ``allocation_id`` depending
        on if you're associating a VPC address or a plain EC2 address.

        When using an Allocation ID, make sure to pass ``None`` for ``public_ip``
        as EC2 expects a single parameter and if ``public_ip`` is passed boto
        will preference that instead of ``allocation_id``.

        :type instance_id: string
        :param instance_id: The ID of the instance

        :type public_ip: string
        :param public_ip: The public IP address for EC2 based allocations.

        :type allocation_id: string
        :param allocation_id: The allocation ID for a VPC-based elastic IP.

        :type network_interface_id: string
        :param network_interface_id: The network interface ID to which
            elastic IP is to be assigned to

        :type private_ip_address: string
        :param private_ip_address: The primary or secondary private IP address
            to associate with the Elastic IP address.

        :type allow_reassociation: bool
        :param allow_reassociation: Specify this option to allow an Elastic IP
            address that is already associated with another network interface
            or instance to be re-associated with the specified instance or
            interface.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: class:`boto.ec2.address.Address`
        :return: The associated address instance
        Fr$  r%  r&  rH   rH   rI   associate_address_object  s    *  z&EC2Connection.associate_address_objectc                 C   sB   i }|dk	r||d< n|dk	r&||d< |r2d|d< | j d|ddS )	a  
        Disassociate an Elastic IP address from a currently running instance.

        :type public_ip: string
        :param public_ip: The public IP address for EC2 elastic IPs.

        :type association_id: string
        :param association_id: The association ID for a VPC based elastic ip.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: True if successful
        NZAssociationIdr  r_   r`   ZDisassociateAddressrc   rd   r   )r8   r   Zassociation_idrj   rL   rH   rH   rI   disassociate_address  s    
z"EC2Connection.disassociate_addressc                 C   sB   i }|dk	r||d< n|dk	r&||d< |r2d|d< | j d|ddS )	a  
        Free up an Elastic IP address.  Pass a public IP address to
        release an EC2 Elastic IP address and an AllocationId to
        release a VPC Elastic IP address.  You should only pass
        one value.

        This requires one of ``public_ip`` or ``allocation_id`` depending
        on if you're associating a VPC address or a plain EC2 address.

        When using an Allocation ID, make sure to pass ``None`` for ``public_ip``
        as EC2 expects a single parameter and if ``public_ip`` is passed boto
        will preference that instead of ``allocation_id``.

        :type public_ip: string
        :param public_ip: The public IP address for EC2 elastic IPs.

        :type allocation_id: string
        :param allocation_id: The Allocation ID for VPC elastic IPs.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: True if successful
        Nr  r  r_   r`   ZReleaseAddressrc   rd   r   )r8   r   r!  rj   rL   rH   rH   rI   release_address   s    
zEC2Connection.release_addressc                 C   sF   i }|dk	r||d< |dk	r*|  ||d |r6d|d< | jd|ddS )	a  
        Unassigns one or more secondary private IP addresses from a network
        interface in Amazon VPC.

        :type network_interface_id: string
        :param network_interface_id: The network interface from which the
            secondary private IP address will be unassigned.

        :type private_ip_addresses: list
        :param private_ip_addresses: Specifies the secondary private IP
            addresses that you want to unassign from the network interface.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: True if successful
        Nr   r   r_   r`   ZUnassignPrivateIpAddressesrc   rd   r   )r8   r  r  rj   rL   rH   rH   rI   unassign_private_ip_addresses'  s    z+EC2Connection.unassign_private_ip_addressesc                 C   sJ   i }|r|  ||d |r&| || |r2d|d< | jd|dtfgddS )a  
        Get all Volumes associated with the current credentials.

        :type volume_ids: list
        :param volume_ids: Optional list of volume ids.  If this list
                           is present, only the volumes associated with
                           these volume ids will be returned.

        :type filters: dict
        :param filters: Optional filters that can be used to limit
                        the results returned.  Filters are provided
                        in the form of a dictionary consisting of
                        filter names as the key and filter values
                        as the value.  The set of allowable filter
                        names/values is dependent on the request
                        being performed.  Check the EC2 API guide
                        for details.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list of :class:`boto.ec2.volume.Volume`
        :return: The requested Volume objects
        VolumeIdr_   r`   ZDescribeVolumesrb   rc   rd   )rf   r\   rg   r   )r8   
volume_idsrW   rj   rL   rH   rH   rI   get_all_volumesL  s     zEC2Connection.get_all_volumesc                 C   s\   i }|r|  ||d |r"||d< |r.||d< |r>| || |rJd|d< | jd|tddS )	a  
        Retrieve the status of one or more volumes.

        :type volume_ids: list
        :param volume_ids: A list of strings of volume IDs

        :type max_results: int
        :param max_results: The maximum number of paginated instance
            items per response.

        :type next_token: str
        :param next_token: A string specifying the next paginated set
            of results to return.

        :type filters: dict
        :param filters: Optional filters that can be used to limit
            the results returned.  Filters are provided
            in the form of a dictionary consisting of
            filter names as the key and filter values
            as the value.  The set of allowable filter
            names/values is dependent on the request
            being performed.  Check the EC2 API guide
            for details.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of volume status.
        r,  r   r   r_   r`   ZDescribeVolumeStatusrc   rd   )rf   r\   rz   r&   )r8   r-  r   r   rW   rj   rL   rH   rH   rI   get_all_volume_statuso  s    ! z#EC2Connection.get_all_volume_statusc                 C   s$   d|i}|rd|d< | j d|ddS )a  
        Enables I/O operations for a volume that had I/O operations
        disabled because the data on the volume was potentially inconsistent.

        :type volume_id: str
        :param volume_id: The ID of the volume.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: True if successful
        r,  r_   r`   ZEnableVolumeIOrc   rd   r   r8   	volume_idrj   rL   rH   rH   rI   enable_volume_io  s    zEC2Connection.enable_volume_ioautoEnableIOc                 C   s(   ||d}|rd|d< | j d|tddS )a  
        Describes attribute of the volume.

        :type volume_id: str
        :param volume_id: The ID of the volume.

        :type attribute: str
        :param attribute: The requested attribute.  Valid values are:

            * autoEnableIO

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list of :class:`boto.ec2.volume.VolumeAttribute`
        :return: The requested Volume attribute
        )r,  r   r_   r`   ZDescribeVolumeAttributerc   rd   )rz   r   )r8   r1  r   rj   rL   rH   rH   rI   get_volume_attribute  s    
 z"EC2Connection.get_volume_attributec                 C   s4   d|i}|dkr||d< |r$d|d< | j d|ddS )	a  
        Changes an attribute of an Volume.

        :type volume_id: string
        :param volume_id: The volume id you wish to change

        :type attribute: string
        :param attribute: The attribute you wish to change.  Valid values are:
            AutoEnableIO.

        :type new_value: string
        :param new_value: The new value of the attribute.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        r,  ZAutoEnableIOzAutoEnableIO.Valuer_   r`   ZModifyVolumeAttributerc   rd   r   )r8   r1  r   	new_valuerj   rL   rH   rH   rI   modify_volume_attribute  s    z%EC2Connection.modify_volume_attributec	           
      C   s   t |tr|j}d|i}	|r$||	d< |r@t |tr8|j}||	d< |rL||	d< |r\t||	d< |rtd|	d< |rt||	d< |rd|	d	< | jd
|	tddS )a  
        Create a new EBS Volume.

        :type size: int
        :param size: The size of the new volume, in GiB

        :type zone: string or :class:`boto.ec2.zone.Zone`
        :param zone: The availability zone in which the Volume will be created.

        :type snapshot: string or :class:`boto.ec2.snapshot.Snapshot`
        :param snapshot: The snapshot from which the new Volume will be
            created.

        :type volume_type: string
        :param volume_type: The type of the volume. (optional).  Valid
            values are: standard | io1 | gp2.

        :type iops: int
        :param iops: The provisioned IOPS you want to associate with
            this volume. (optional)

        :type encrypted: bool
        :param encrypted: Specifies whether the volume should be encrypted.
            (optional)

        :type kms_key_id: string
        :params kms_key_id: If encrypted is True, this KMS Key ID may be specified to
            encrypt volume with this key (optional)
            e.g.: arn:aws:kms:us-east-1:012345678910:key/abcd1234-a123-456a-a12b-a123b4cd56ef

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        r  Size
SnapshotIdZ
VolumeTypeZIopsr_   	EncryptedKmsKeyIdr`   ZCreateVolumerc   rd   )rR   r   rM   r   r   strrz   r   )
r8   sizezonesnapshotZvolume_typeZiops	encrypted
kms_key_idrj   rL   rH   rH   rI   create_volume  s(    $

zEC2Connection.create_volumec                 C   s$   d|i}|rd|d< | j d|ddS )a'  
        Delete an EBS volume.

        :type volume_id: str
        :param volume_id: The ID of the volume to be delete.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: True if successful
        r,  r_   r`   ZDeleteVolumerc   rd   r   r0  rH   rH   rI   delete_volume	  s    zEC2Connection.delete_volumec                 C   s(   |||d}|rd|d< | j d|ddS )ao  
        Attach an EBS volume to an EC2 instance.

        :type volume_id: str
        :param volume_id: The ID of the EBS volume to be attached.

        :type instance_id: str
        :param instance_id: The ID of the EC2 instance to which it will
                            be attached.

        :type device: str
        :param device: The device on the instance through which the
                       volume will be exposted (e.g. /dev/sdh)

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: True if successful
        )r   r,  Devicer_   r`   ZAttachVolumerc   rd   r   )r8   r1  r   devicerj   rL   rH   rH   rI   attach_volume/	  s    zEC2Connection.attach_volumec                 C   sH   d|i}|r||d< |r ||d< |r,d|d< |r8d|d< | j d|dd	S )
ag  
        Detach an EBS volume from an EC2 instance.

        :type volume_id: str
        :param volume_id: The ID of the EBS volume to be attached.

        :type instance_id: str
        :param instance_id: The ID of the EC2 instance from which it will
            be detached.

        :type device: str
        :param device: The device on the instance through which the
            volume is exposted (e.g. /dev/sdh)

        :type force: bool
        :param force: Forces detachment if the previous detachment
            attempt did not occur cleanly.  This option can lead to
            data loss or a corrupted file system. Use this option only
            as a last resort to detach a volume from a failed
            instance. The instance will not have an opportunity to
            flush file system caches nor file system meta data. If you
            use this option, you must perform file system check and
            repair procedures.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: True if successful
        r,  r   rC  r_   r   r`   ZDetachVolumerc   rd   r   )r8   r1  r   rD  r   rj   rL   rH   rH   rI   detach_volumeK	  s     zEC2Connection.detach_volumec                 C   sn   i }|r|  ||d |r(|  ||d |r:|  ||d |rJ| || |rVd|d< | jd|dtfgdd	S )
a  
        Get all EBS Snapshots associated with the current credentials.

        :type snapshot_ids: list
        :param snapshot_ids: Optional list of snapshot ids.  If this list is
                             present, only the Snapshots associated with
                             these snapshot ids will be returned.

        :type owner: str or list
        :param owner: If present, only the snapshots owned by the specified user(s)
                      will be returned.  Valid values are:

                      * self
                      * amazon
                      * AWS Account ID

        :type restorable_by: str or list
        :param restorable_by: If present, only the snapshots that are restorable
                              by the specified account id(s) will be returned.

        :type filters: dict
        :param filters: Optional filters that can be used to limit
                        the results returned.  Filters are provided
                        in the form of a dictionary consisting of
                        filter names as the key and filter values
                        as the value.  The set of allowable filter
                        names/values is dependent on the request
                        being performed.  Check the EC2 API guide
                        for details.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list of :class:`boto.ec2.snapshot.Snapshot`
        :return: The requested Snapshot objects
        r8  r^   ZRestorableByr_   r`   ZDescribeSnapshotsrb   rc   rd   )rf   r\   rg   r   )r8   Zsnapshot_idsownerZrestorable_byrW   rj   rL   rH   rH   rI   get_all_snapshotsx	  s    ' zEC2Connection.get_all_snapshotsc                 C   sn   d|i}|r|dd |d< |r(d|d< | j d|tdd	}| j|g|d
d }|jd}|rj|d| |S )a  
        Create a snapshot of an existing EBS Volume.

        :type volume_id: str
        :param volume_id: The ID of the volume to be snapshot'ed

        :type description: str
        :param description: A description of the snapshot.
                            Limited to 255 characters.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: :class:`boto.ec2.snapshot.Snapshot`
        :return: The created Snapshot object
        r,  r      ru   r_   r`   ZCreateSnapshotrc   rd   rj   rt   )rz   r   r.  tagsr   Zadd_tag)r8   r1  r{   rj   rL   r>  volumevolume_namerH   rH   rI   create_snapshot	  s     zEC2Connection.create_snapshotc                 C   s$   d|i}|rd|d< | j d|ddS )r   r8  r_   r`   ZDeleteSnapshotrc   rd   r   )r8   rx   rj   rL   rH   rH   rI   r   	  s    zEC2Connection.delete_snapshotc                 C   s>   ||d}|dk	r||d< |r&d|d< | j d|tdd}|jS )	a  
        Copies a point-in-time snapshot of an Amazon Elastic Block Store
        (Amazon EBS) volume and stores it in Amazon Simple Storage Service
        (Amazon S3). You can copy the snapshot within the same region or from
        one region to another. You can use the snapshot to create new Amazon
        EBS volumes or Amazon Machine Images (AMIs).


        :type source_region: str
        :param source_region: The ID of the AWS region that contains the
            snapshot to be copied (e.g 'us-east-1', 'us-west-2', etc.).

        :type source_snapshot_id: str
        :param source_snapshot_id: The ID of the Amazon EBS snapshot to copy

        :type description: str
        :param description: A description of the new Amazon EBS snapshot.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: str
        :return: The snapshot ID

        )SourceRegionZSourceSnapshotIdNru   r_   r`   ZCopySnapshotrc   rd   )rz   r   r   )r8   source_regionZsource_snapshot_idr{   rj   rL   r>  rH   rH   rI   copy_snapshot	  s    
zEC2Connection.copy_snapshot         c              
   C   s  t  }t |j|j|j|j}t |j|j|j}t |j|j|jt| d d d }t |j|jd}	g }
t ddd}td|D ]}|
	|t|d  qtd|D ]}|
	|t|d  qtd|D ]}|
	|t|d  qtdd}d}|	|kr<|dks||k r<|
	|	 |d7 }|	|8 }	t |	j|	jd}	qg }|
D ] }|
|d	krD|	| qDt|}
| jd
d}|jdd d i }|D ]>}|jd}|r||}|sg }|||< |	| q|D ]}|| }|dd }d}d	}|D ]}d}|r||
 k rt |jd}||
| k r|dkr|jdsz,| |j tjd|jd |jf  W n2 tk
r   tjd|jd |jf  Y nX nd}d	}n|d7 }d	}qqqdS )a  
        Trim excess snapshots, based on when they were taken. More current
        snapshots are retained, with the number retained decreasing as you
        move back in time.

        If ebs volumes have a 'Name' tag with a value, their snapshots
        will be assigned the same tag when they are created. The values
        of the 'Name' tags for snapshots are used by this function to
        group snapshots taken from the same volume (or from a series
        of like-named volumes over time) for trimming.

        For every group of like-named snapshots, this function retains
        the newest and oldest snapshots, as well as, by default,  the
        first snapshots taken in each of the last eight hours, the first
        snapshots taken in each of the last seven days, the first snapshots
        taken in the last 4 weeks (counting Midnight Sunday morning as
        the start of the week), and the first snapshot from the first
        day of each month forever.

        :type hourly_backups: int
        :param hourly_backups: How many recent hourly backups should be saved.

        :type daily_backups: int
        :param daily_backups: How many recent daily backups should be saved.

        :type weekly_backups: int
        :param weekly_backups: How many recent weekly backups should be saved.

        :type monthly_backups: int
        :param monthly_backups: How many monthly backups should be saved. Use True for no limit.
        rO   rS  )daysi  r   )hours)weeksTFr8   )rG  c                 S   s   | j S )N)r  )xrH   rH   rI   <lambda>]
      z.EC2Connection.trim_snapshots.<locals>.<lambda>)r   rt   Nz%Y-%m-%dT%H:%M:%S.000ZZpreserve_snapshotzTrimmed snapshot %s (%s)zmAttempt to trim snapshot %s (%s) failed. Possible result of a race condition with trimming on another server?)r   utcnowyearmonthdayhourr   weekdayranger   __contains__sortedrH  sortrK  r   __len__strptimer  r   r   botologinfor,   error)r8   Zhourly_backupsZdaily_backupsZweekly_backupsZmonthly_backupsnowZ	last_hourZlast_midnightZlast_sundayZstart_of_monthZtarget_backup_timesZoldest_snapshot_dater`  r_  weekZone_dayZmonthly_snapshots_addedtemptZall_snapshotsZsnaps_for_each_volumeZsnaprM  Zsnaps_for_volumeZsnapsZtime_period_numberZsnap_found_for_this_time_periodZcheck_this_snapZ	snap_daterH   rH   rI   trim_snapshots	  s    -(


 

 $zEC2Connection.trim_snapshotscreateVolumePermissionc                 C   s2   d|i}|r||d< |r d|d< | j d|tddS )aR  
        Get information about an attribute of a snapshot.  Only one attribute
        can be specified per call.

        :type snapshot_id: str
        :param snapshot_id: The ID of the snapshot.

        :type attribute: str
        :param attribute: The requested attribute.  Valid values are:

                          * createVolumePermission

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list of :class:`boto.ec2.snapshotattribute.SnapshotAttribute`
        :return: The requested Snapshot attribute
        r   r8  r_   r`   ZDescribeSnapshotAttributerc   rd   )rz   r   r8   rx   r   rj   rL   rH   rH   rI   get_snapshot_attribute
  s     z$EC2Connection.get_snapshot_attributec                 C   sL   |||d}|r|  ||d |r0|  ||d |r<d|d< | jd|ddS )	a  
        Changes an attribute of an image.

        :type snapshot_id: string
        :param snapshot_id: The snapshot id you wish to change

        :type attribute: string
        :param attribute: The attribute you wish to change.  Valid values are:
            createVolumePermission

        :type operation: string
        :param operation: Either add or remove (this is required for changing
            snapshot ermissions)

        :type user_ids: list
        :param user_ids: The Amazon IDs of users to add/remove attributes

        :type groups: list
        :param groups: The groups to add/remove attributes.  The only valid
            value at this time is 'all'.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        )r8  r   r   r   r   r_   r`   ZModifySnapshotAttributerc   rd   r   )r8   rx   r   r   r   r   rj   rL   rH   rH   rI   modify_snapshot_attribute
  s    z'EC2Connection.modify_snapshot_attributec                 C   s&   ||d}|rd|d< | j d|ddS )a  
        Resets an attribute of a snapshot to its default value.

        :type snapshot_id: string
        :param snapshot_id: ID of the snapshot

        :type attribute: string
        :param attribute: The attribute to reset

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: Whether the operation succeeded or not
        )r8  r   r_   r`   ZResetSnapshotAttributerc   rd   r   rr  rH   rH   rI   reset_snapshot_attribute
  s    z&EC2Connection.reset_snapshot_attributec                 C   sJ   i }|r|  ||d |r&| || |r2d|d< | jd|dtfgddS )aF  
        Get all key pairs associated with your account.

        :type keynames: list
        :param keynames: A list of the names of keypairs to retrieve.
            If not provided, all key pairs will be returned.

        :type filters: dict
        :param filters: Optional filters that can be used to limit the
            results returned.  Filters are provided in the form of a
            dictionary consisting of filter names as the key and
            filter values as the value.  The set of allowable filter
            names/values is dependent on the request being performed.
            Check the EC2 API guide for details.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of :class:`boto.ec2.keypair.KeyPair`
        r   r_   r`   ZDescribeKeyPairsrb   rc   rd   )rf   r\   rg   r   )r8   keynamesrW   rj   rL   rH   rH   rI   get_all_key_pairs
  s     zEC2Connection.get_all_key_pairsc              
   C   sV   z| j |g|dd W S  | jk
rP } z|jdkr>W Y 
dS  W 5 d}~X Y nX dS )a  
        Convenience method to retrieve a specific keypair (KeyPair).

        :type keyname: string
        :param keyname: The name of the keypair to retrieve

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: :class:`boto.ec2.keypair.KeyPair`
        :return: The KeyPair specified or None if it is not found
        )rv  rj   r   zInvalidKeyPair.NotFoundN)rw  ResponseErrorcode)r8   keynamerj   erH   rH   rI   get_key_pair  s    

zEC2Connection.get_key_pairc                 C   s&   d|i}|rd|d< | j d|tddS )ac  
        Create a new key pair for your account.
        This will create the key pair within the region you
        are currently connected to.

        :type key_name: string
        :param key_name: The name of the new keypair

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: :class:`boto.ec2.keypair.KeyPair`
        :return: The newly created :class:`boto.ec2.keypair.KeyPair`.
                 The material attribute of the new KeyPair object
                 will contain the the unencrypted PEM encoded RSA private key.
        r   r_   r`   ZCreateKeyPairrc   rd   )rz   r   r8   r   rj   rL   rH   rH   rI   create_key_pair.  s    zEC2Connection.create_key_pairc                 C   s$   d|i}|rd|d< | j d|ddS )z
        Delete a key pair from your account.

        :type key_name: string
        :param key_name: The name of the keypair to delete

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        r   r_   r`   ZDeleteKeyPairrc   rd   r   r}  rH   rH   rI   delete_key_pairD  s    zEC2Connection.delete_key_pairc                 C   s2   t |}||d}|r d|d< | jd|tddS )a  
        imports the public key from an RSA key pair that you created
        with a third-party tool.

        Supported formats:

        * OpenSSH public key format (e.g., the format
          in ~/.ssh/authorized_keys)

        * Base64 encoded DER format

        * SSH public key file format as specified in RFC4716

        DSA keys are not supported. Make sure your key generator is
        set up to create RSA keys.

        Supported lengths: 1024, 2048, and 4096.

        :type key_name: string
        :param key_name: The name of the new keypair

        :type public_key_material: string
        :param public_key_material: The public key. You must base64 encode
                                    the public key material before sending
                                    it to AWS.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: :class:`boto.ec2.keypair.KeyPair`
        :return: A :class:`boto.ec2.keypair.KeyPair` object representing
            the newly imported key pair.  This object will contain only
            the key name and the fingerprint.
        )r   ZPublicKeyMaterialr_   r`   ZImportKeyPairrc   rd   )r   r   rz   r   )r8   r   Zpublic_key_materialrj   rL   rH   rH   rI   import_key_pairT  s    #
zEC2Connection.import_key_pairc                 C   sh   i }|dk	r|  ||d |dk	r0|  ||d |dk	rD| || |rPd|d< | jd|dtfgdd	S )
a  
        Get all security groups associated with your account in a region.

        :type groupnames: list
        :param groupnames: A list of the names of security groups to retrieve.
                           If not provided, all security groups will be
                           returned.

        :type group_ids: list
        :param group_ids: A list of IDs of security groups to retrieve for
                          security groups within a VPC.

        :type filters: dict
        :param filters: Optional filters that can be used to limit
                        the results returned.  Filters are provided
                        in the form of a dictionary consisting of
                        filter names as the key and filter values
                        as the value.  The set of allowable filter
                        names/values is dependent on the request
                        being performed.  Check the EC2 API guide
                        for details.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of :class:`boto.ec2.securitygroup.SecurityGroup`
        N	GroupNameGroupIdr_   r`   ZDescribeSecurityGroupsrb   rc   rd   )rf   r\   rg   r   )r8   
groupnamesZ	group_idsrW   rj   rL   rH   rH   rI   get_all_security_groups  s     z%EC2Connection.get_all_security_groupsc                 C   sV   ||d}|dk	r||d< |r&d|d< | j d|tdd}||_||_|dk	rR||_|S )	a  
        Create a new security group for your account.
        This will create the security group within the region you
        are currently connected to.

        :type name: string
        :param name: The name of the new security group

        :type description: string
        :param description: The description of the new security group

        :type vpc_id: string
        :param vpc_id: The ID of the VPC to create the security group in,
                       if any.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: :class:`boto.ec2.securitygroup.SecurityGroup`
        :return: The newly created :class:`boto.ec2.securitygroup.SecurityGroup`.
        )r  ZGroupDescriptionNVpcIdr_   r`   ZCreateSecurityGrouprc   rd   )rz   r   rM   r{   vpc_id)r8   rM   r{   r  rj   rL   r   rH   rH   rI   create_security_group  s      z#EC2Connection.create_security_groupc                 C   sB   i }|dk	r||d< n|dk	r&||d< |r2d|d< | j d|ddS )	a  
        Delete a security group from your account.

        :type name: string
        :param name: The name of the security group to delete.

        :type group_id: string
        :param group_id: The ID of the security group to delete within
          a VPC.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: True if successful.
        Nr  r  r_   r`   ZDeleteSecurityGrouprc   rd   r   )r8   rM   group_idrj   rL   rH   rH   rI   delete_security_group  s    
z#EC2Connection.delete_security_groupc	           
      C   sh   d|i}	|r||	d< |r ||	d< |r,||	d< |r8||	d< |rD||	d< |rP||	d< |r\d|	d	< |  d
|	S )a  
        NOTE: This method uses the old-style request parameters
              that did not allow a port to be specified when
              authorizing a group.

        :type group_name: string
        :param group_name: The name of the security group you are adding
            the rule to.

        :type src_security_group_name: string
        :param src_security_group_name: The name of the security group you are
            granting access to.

        :type src_security_group_owner_id: string
        :param src_security_group_owner_id: The ID of the owner of the security
            group you are granting access to.

        :type ip_protocol: string
        :param ip_protocol: Either tcp | udp | icmp

        :type from_port: int
        :param from_port: The beginning port number you are enabling

        :type to_port: int
        :param to_port: The ending port number you are enabling

        :type to_port: string
        :param to_port: The CIDR block you are providing access to.
            See http://goo.gl/Yj5QC

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: True if successful.
        r  SourceSecurityGroupNameSourceSecurityGroupOwnerId
IpProtocolFromPortToPortCidrIpr_   r`   AuthorizeSecurityGroupIngressr   
r8   
group_namesrc_security_group_namesrc_security_group_owner_idip_protocol	from_portto_portcidr_iprj   rL   rH   rH   rI   #authorize_security_group_deprecated  s     *z1EC2Connection.authorize_security_group_deprecatedc                 C   s   |r*|dkr*|dkr*|dkr*|  |||S i }|r:||d< |rF||d< |rVd}|||< |rfd}|||< |	rvd}|	||< |r||d< |dk	r||d< |dk	r||d	< |rt|ts|g}t|D ]\}}||d
|d  < q|
rd|d< | jd|ddS )a:  
        Add a new rule to an existing security group.
        You need to pass in either src_security_group_name and
        src_security_group_owner_id OR ip_protocol, from_port, to_port,
        and cidr_ip.  In other words, either you are authorizing another
        group or you are authorizing some ip-based rule.

        :type group_name: string
        :param group_name: The name of the security group you are adding
            the rule to.

        :type src_security_group_name: string
        :param src_security_group_name: The name of the security group you are
            granting access to.

        :type src_security_group_owner_id: string
        :param src_security_group_owner_id: The ID of the owner of the security
            group you are granting access to.

        :type ip_protocol: string
        :param ip_protocol: Either tcp | udp | icmp

        :type from_port: int
        :param from_port: The beginning port number you are enabling

        :type to_port: int
        :param to_port: The ending port number you are enabling

        :type cidr_ip: string or list of strings
        :param cidr_ip: The CIDR block you are providing access to.
            See http://goo.gl/Yj5QC

        :type group_id: string
        :param group_id: ID of the EC2 or VPC security group to
            modify.  This is required for VPC security groups and can
            be used instead of group_name for EC2 security groups.

        :type src_security_group_group_id: string
        :param src_security_group_group_id: The ID of the security
            group you are granting access to.  Can be used instead of
            src_security_group_name

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: True if successful.
        Nr  r  "IpPermissions.1.Groups.1.GroupNameIpPermissions.1.Groups.1.UserId IpPermissions.1.Groups.1.GroupIdIpPermissions.1.IpProtocolIpPermissions.1.FromPortIpPermissions.1.ToPortz"IpPermissions.1.IpRanges.%d.CidrIprO   r_   r`   r  rc   rd   )r  rR   rV   r   r   )r8   r  r  r  r  r  r  r  r  src_security_group_group_idrj   rL   
param_namerX   Zsingle_cidr_iprH   rH   rI   authorize_security_group*  sN    8 
 z&EC2Connection.authorize_security_groupc           	      C   sf   ||d}|dk	r||d< |dk	r*||d< |dk	r:||d< |dk	rJ||d< |rVd|d< | j d	|d
dS )a  
        The action adds one or more egress rules to a VPC security
        group. Specifically, this action permits instances in a
        security group to send traffic to one or more destination
        CIDR IP address ranges, or to one or more destination
        security groups in the same VPC.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        )r  r  Nr  r  r  !IpPermissions.1.IpRanges.1.CidrIpr_   r`   ZAuthorizeSecurityGroupEgressrc   rd   r   	r8   r  r  r  r  Zsrc_group_idr  rj   rL   rH   rH   rI   authorize_security_group_egress  s"     z-EC2Connection.authorize_security_group_egressc	           
      C   sh   d|i}	|r||	d< |r ||	d< |r,||	d< |r8||	d< |rD||	d< |rP||	d< |r\d|	d	< |  d
|	S )a\  
        NOTE: This method uses the old-style request parameters
              that did not allow a port to be specified when
              authorizing a group.

        Remove an existing rule from an existing security group.
        You need to pass in either src_security_group_name and
        src_security_group_owner_id OR ip_protocol, from_port, to_port,
        and cidr_ip.  In other words, either you are revoking another
        group or you are revoking some ip-based rule.

        :type group_name: string
        :param group_name: The name of the security group you are removing
                           the rule from.

        :type src_security_group_name: string
        :param src_security_group_name: The name of the security group you are
                                        revoking access to.

        :type src_security_group_owner_id: string
        :param src_security_group_owner_id: The ID of the owner of the security
                                            group you are revoking access to.

        :type ip_protocol: string
        :param ip_protocol: Either tcp | udp | icmp

        :type from_port: int
        :param from_port: The beginning port number you are disabling

        :type to_port: int
        :param to_port: The ending port number you are disabling

        :type to_port: string
        :param to_port: The CIDR block you are revoking access to.
                        http://goo.gl/Yj5QC

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: True if successful.
        r  r  r  r  r  r  r  r_   r`   RevokeSecurityGroupIngressr   r  rH   rH   rI    revoke_security_group_deprecated  s     0z.EC2Connection.revoke_security_group_deprecatedc                 C   s   |r*|dkr*|dkr*|dkr*|  |||S i }|dk	r>||d< |dk	rN||d< |r^d}|||< |	rnd}|	||< |r~d}|||< |r||d< |dk	r||d< |dk	r||d	< |r||d
< |
rd|d< | jd|ddS )a8  
        Remove an existing rule from an existing security group.
        You need to pass in either src_security_group_name and
        src_security_group_owner_id OR ip_protocol, from_port, to_port,
        and cidr_ip.  In other words, either you are revoking another
        group or you are revoking some ip-based rule.

        :type group_name: string
        :param group_name: The name of the security group you are removing
            the rule from.

        :type src_security_group_name: string
        :param src_security_group_name: The name of the security group you are
            revoking access to.

        :type src_security_group_owner_id: string
        :param src_security_group_owner_id: The ID of the owner of the security
            group you are revoking access to.

        :type ip_protocol: string
        :param ip_protocol: Either tcp | udp | icmp

        :type from_port: int
        :param from_port: The beginning port number you are disabling

        :type to_port: int
        :param to_port: The ending port number you are disabling

        :type cidr_ip: string
        :param cidr_ip: The CIDR block you are revoking access to.
            See http://goo.gl/Yj5QC

        :type group_id: string
        :param group_id: ID of the EC2 or VPC security group to
            modify.  This is required for VPC security groups and can
            be used instead of group_name for EC2 security groups.

        :type src_security_group_group_id: string
        :param src_security_group_group_id: The ID of the security group
            for which you are revoking access.  Can be used instead
            of src_security_group_name

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: True if successful.
        Nr  r  r  r  r  r  r  r  r  r_   r`   r  rc   rd   )r  r   )r8   r  r  r  r  r  r  r  r  r  rj   rL   r  rH   rH   rI   revoke_security_group  sF    6  z#EC2Connection.revoke_security_groupc           	      C   st   i }|r||d< |r||d< |dk	r,||d< |dk	r<||d< |dk	rL||d< |rX||d< |rdd|d	< | j d
|ddS )a|  
        Remove an existing egress rule from an existing VPC security
        group.  You need to pass in an ip_protocol, from_port and
        to_port range only if the protocol you are using is
        port-based. You also need to pass in either a src_group_id or
        cidr_ip.

        :type group_name: string
        :param group_id:  The name of the security group you are removing
            the rule from.

        :type ip_protocol: string
        :param ip_protocol: Either tcp | udp | icmp | -1

        :type from_port: int
        :param from_port: The beginning port number you are disabling

        :type to_port: int
        :param to_port: The ending port number you are disabling

        :type src_group_id: src_group_id
        :param src_group_id: The source security group you are
            revoking access to.

        :type cidr_ip: string
        :param cidr_ip: The CIDR block you are revoking access to.
            See http://goo.gl/Yj5QC

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: True if successful.
        r  r  Nr  r  r  r  r_   r`   ZRevokeSecurityGroupEgressrc   rd   r   r  rH   rH   rI   revoke_security_group_egressF  s&    * z*EC2Connection.revoke_security_group_egressc                 C   s^   i }|r|  ||d |r&| || |r2d|d< | jd|dtfgdd}|D ]
}t|_qN|S )a~  
        Get all available regions for the EC2 service.

        :type region_names: list of str
        :param region_names: Names of regions to limit output

        :type filters: dict
        :param filters: Optional filters that can be used to limit
                        the results returned.  Filters are provided
                        in the form of a dictionary consisting of
                        filter names as the key and filter values
                        as the value.  The set of allowable filter
                        names/values is dependent on the request
                        being performed.  Check the EC2 API guide
                        for details.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of :class:`boto.ec2.regioninfo.RegionInfo`
        Z
RegionNamer_   r`   ZDescribeRegionsrb   rc   rd   )rf   r\   rg   r   r.   Zconnection_cls)r8   Zregion_namesrW   rj   rL   Zregionsr4   rH   rH   rI   get_all_regions  s     zEC2Connection.get_all_regionsc                 C   s  i }|dk	r|  ||d |r&||d< |r2||d< |r>||d< |rN| || |dk	r^||d< |dk	rn||d< |dk	r|rd|d	< nd
|d	< |	dk	rt|	|d< |
dk	rt|
|d< |dk	rt||d< |dk	r||d< |dk	rt||d< |rd|d< | jd|dtfgddS )a
  
        Describes Reserved Instance offerings that are available for purchase.

        :type reserved_instances_offering_ids: list
        :param reserved_instances_id: One or more Reserved Instances
            offering IDs.

        :type instance_type: str
        :param instance_type: Displays Reserved Instances of the specified
                              instance type.

        :type availability_zone: str
        :param availability_zone: Displays Reserved Instances within the
                                  specified Availability Zone.

        :type product_description: str
        :param product_description: Displays Reserved Instances with the
                                    specified product description.

        :type filters: dict
        :param filters: Optional filters that can be used to limit
                        the results returned.  Filters are provided
                        in the form of a dictionary consisting of
                        filter names as the key and filter values
                        as the value.  The set of allowable filter
                        names/values is dependent on the request
                        being performed.  Check the EC2 API guide
                        for details.

        :type instance_tenancy: string
        :param instance_tenancy: The tenancy of the Reserved Instance offering.
            A Reserved Instance with tenancy of dedicated will run on
            single-tenant hardware and can only be launched within a VPC.

        :type offering_type: string
        :param offering_type: The Reserved Instance offering type.  Valid
            Values: `"Heavy Utilization" | "Medium Utilization" | "Light
            Utilization"`

        :type include_marketplace: bool
        :param include_marketplace: Include Marketplace offerings in the
            response.

        :type min_duration: int :param min_duration: Minimum duration (in
            seconds) to filter when searching for offerings.

        :type max_duration: int
        :param max_duration: Maximum duration (in seconds) to filter when
            searching for offerings.

        :type max_instance_count: int
        :param max_instance_count: Maximum number of instances to filter when
            searching for offerings.

        :type next_token: string
        :param next_token: Token to use when requesting the next paginated set
            of offerings.

        :type max_results: int
        :param max_results: Maximum number of offerings to return per call.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of
            :class:`boto.ec2.reservedinstance.ReservedInstancesOffering`.

        NReservedInstancesOfferingIdr$   r  r   ZInstanceTenancyZOfferingTyper_   ZIncludeMarketplacer   ZMinDurationZMaxDurationZMaxInstanceCountr   r   r`   Z"DescribeReservedInstancesOfferingsrb   rc   rd   )rf   r\   r;  rg   r   )r8   Zreserved_instances_offering_idsr   r  r  rW   Zinstance_tenancyZoffering_typeZinclude_marketplaceZmin_durationZmax_durationZmax_instance_countr   r   rj   rL   rH   rH   rI   $get_all_reserved_instances_offerings  sL    T
 z2EC2Connection.get_all_reserved_instances_offeringsc                 C   sJ   i }|r|  ||d |r&| || |r2d|d< | jd|dtfgddS )a  
        Describes one or more of the Reserved Instances that you purchased.

        :type reserved_instance_ids: list
        :param reserved_instance_ids: A list of the reserved instance ids that
            will be returned. If not provided, all reserved instances
            will be returned.

        :type filters: dict
        :param filters: Optional filters that can be used to limit the
            results returned.  Filters are provided in the form of a
            dictionary consisting of filter names as the key and
            filter values as the value.  The set of allowable filter
            names/values is dependent on the request being performed.
            Check the EC2 API guide for details.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of :class:`boto.ec2.reservedinstance.ReservedInstance`
        ReservedInstancesIdr_   r`   ZDescribeReservedInstancesrb   rc   rd   )rf   r\   rg   r   )r8   reserved_instances_idrW   rj   rL   rH   rH   rI   get_all_reserved_instances(  s      z(EC2Connection.get_all_reserved_instancesc                 C   sP   ||d}|dk	r2t |d |d< t |d |d< |r>d|d< | jd	|td
dS )a  
        Purchase a Reserved Instance for use with your account.
        ** CAUTION **
        This request can result in large amounts of money being charged to your
        AWS account.  Use with caution!

        :type reserved_instances_offering_id: string
        :param reserved_instances_offering_id: The offering ID of the Reserved
            Instance to purchase

        :type instance_count: int
        :param instance_count: The number of Reserved Instances to purchase.
            Default value is 1.

        :type limit_price: tuple
        :param instance_count: Limit the price on the total order.
            Must be a tuple of (amount, currency_code), for example:
            (100.0, 'USD').

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: :class:`boto.ec2.reservedinstance.ReservedInstance`
        :return: The newly created Reserved Instance
        )r  r  Nr   zLimitPrice.AmountrO   zLimitPrice.CurrencyCoder_   r`   Z!PurchaseReservedInstancesOfferingrc   rd   )r;  rz   r   )r8   Zreserved_instances_offering_idinstance_countZlimit_pricerj   rL   rH   rH   rI   #purchase_reserved_instance_offeringK  s     z1EC2Connection.purchase_reserved_instance_offeringc                 C   sn   |t ||d}t|D ]0\}}|\}	}
t |	|d| < t |
|d| < q|rVd|d< | jd|dtfgdd	S )
a	  Creates a new listing for Reserved Instances.

        Creates a new listing for Amazon EC2 Reserved Instances that will be
        sold in the Reserved Instance Marketplace. You can submit one Reserved
        Instance listing at a time.

        The Reserved Instance Marketplace matches sellers who want to resell
        Reserved Instance capacity that they no longer need with buyers who
        want to purchase additional capacity. Reserved Instances bought and
        sold through the Reserved Instance Marketplace work like any other
        Reserved Instances.

        If you want to sell your Reserved Instances, you must first register as
        a Seller in the Reserved Instance Marketplace. After completing the
        registration process, you can create a Reserved Instance Marketplace
        listing of some or all of your Reserved Instances, and specify the
        upfront price you want to receive for them. Your Reserved Instance
        listings then become available for purchase.

        :type reserved_instances_id: string
        :param reserved_instances_id: The ID of the Reserved Instance that
            will be listed.

        :type instance_count: int
        :param instance_count: The number of instances that are a part of a
            Reserved Instance account that will be listed in the Reserved
            Instance Marketplace. This number should be less than or equal to
            the instance count associated with the Reserved Instance ID
            specified in this call.

        :type price_schedules: List of tuples
        :param price_schedules: A list specifying the price of the Reserved
            Instance for each month remaining in the Reserved Instance term.
            Each tuple contains two elements, the price and the term.  For
            example, for an instance that 11 months remaining in its term,
            we can have a price schedule with an upfront price of $2.50.
            At 8 months remaining we can drop the price down to $2.00.
            This would be expressed as::

                price_schedules=[('2.50', 11), ('2.00', 8)]

        :type client_token: string
        :param client_token: Unique, case-sensitive identifier you provide
            to ensure idempotency of the request.  Maximum 64 ASCII characters.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of
            :class:`boto.ec2.reservedinstance.ReservedInstanceListing`

        )r  r  r   zPriceSchedules.%s.PricezPriceSchedules.%s.Termr_   r`   ZCreateReservedInstancesListingrb   rc   rd   )r;  r   rg   r   )r8   r  r  Zprice_schedulesr   rj   rL   rX   scheduler  ZtermrH   rH   rI   !create_reserved_instances_listings  s    9  z/EC2Connection.create_reserved_instances_listingc                 C   s>   i }|dk	r|  ||d |r&d|d< | jd|dtfgddS )	a  Cancels the specified Reserved Instance listing.

        :type reserved_instances_listing_ids: List of strings
        :param reserved_instances_listing_ids: The ID of the
            Reserved Instance listing to be cancelled.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of
            :class:`boto.ec2.reservedinstance.ReservedInstanceListing`

        NZReservedInstancesListingIdr_   r`   ZCancelReservedInstancesListingrb   rc   rd   )rf   rg   r   )r8   Zreserved_instances_listing_idsrj   rL   rH   rH   rI   !cancel_reserved_instances_listing  s      z/EC2Connection.cancel_reserved_instances_listingc                 C   s~   t |D ]p\}}d| }|jd k	r0|j||d < |jd k	rH|j||d < |jd k	r`|j||d < |jd k	r|j||d < qd S )Nz-ReservedInstancesConfigurationSetItemType.%d.r  Platformr  r$   )r   r  platformr  r   )r8   rL   target_configurationsoffsetZtcr
  rH   rH   rI   build_configurations_param_list  s    



z-EC2Connection.build_configurations_param_listc                 C   sV   i }|dk	r||d< |dk	r*|  ||d |dk	r>| || | jd|tdd}|jS )a  
        Modifies the specified Reserved Instances.

        :type client_token: string
        :param client_token: A unique, case-sensitive, token you provide to
                             ensure idempotency of your modification request.

        :type reserved_instance_ids: List of strings
        :param reserved_instance_ids: The IDs of the Reserved Instances to
                                      modify.

        :type target_configurations: List of :class:`boto.ec2.reservedinstance.ReservedInstancesConfiguration`
        :param target_configurations: The configuration settings for the
                                      modified Reserved Instances.

        :rtype: string
        :return: The unique ID for the submitted modification request.
        Nr   r  ZModifyReservedInstancesrc   rd   )rf   r  rz   r   Zmodification_id)r8   r   Zreserved_instance_idsr  rL   ZmrirrH   rH   rI   modify_reserved_instances  s     z'EC2Connection.modify_reserved_instancesc                 C   sJ   i }|r|  ||d |r"||d< |r2| || | jd|dtfgddS )a  
        A request to describe the modifications made to Reserved Instances in
        your account.

        :type reserved_instances_modification_ids: list
        :param reserved_instances_modification_ids: An optional list of
            Reserved Instances modification IDs to describe.

        :type next_token: str
        :param next_token: A string specifying the next paginated set
            of results to return.

        :type filters: dict
        :param filters: Optional filters that can be used to limit the
            results returned.  Filters are provided in the form of a
            dictionary consisting of filter names as the key and
            filter values as the value.  The set of allowable filter
            names/values is dependent on the request being performed.
            Check the EC2 API guide for details.

        :rtype: list
        :return: A list of :class:`boto.ec2.reservedinstance.ReservedInstance`
        ZReservedInstancesModificationIdr   Z&DescribeReservedInstancesModificationsrb   rc   rd   )rf   r\   rg   r   )r8   Z#reserved_instances_modification_idsr   rW   rL   rH   rH   rI   )describe_reserved_instances_modifications  s     z7EC2Connection.describe_reserved_instances_modificationsc                 C   s6   i }|  ||d |rd|d< | jd|dtfgddS )at  
        Enable detailed CloudWatch monitoring for the supplied instances.

        :type instance_id: list of strings
        :param instance_id: The instance ids

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of :class:`boto.ec2.instanceinfo.InstanceInfo`
        r   r_   r`   ZMonitorInstancesrb   rc   rd   rf   rg   r   r   rH   rH   rI   monitor_instances-  s     zEC2Connection.monitor_instancesc                 C   s   | j |g|dS )a  
        Deprecated Version, maintained for backward compatibility.
        Enable detailed CloudWatch monitoring for the supplied instance.

        :type instance_id: string
        :param instance_id: The instance id

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of :class:`boto.ec2.instanceinfo.InstanceInfo`
        rJ  )r  r8   r   rj   rH   rH   rI   monitor_instanceA  s    zEC2Connection.monitor_instancec                 C   s6   i }|  ||d |rd|d< | jd|dtfgddS )ai  
        Disable CloudWatch monitoring for the supplied instance.

        :type instance_id: list of string
        :param instance_id: The instance id

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of :class:`boto.ec2.instanceinfo.InstanceInfo`
        r   r_   r`   ZUnmonitorInstancesrb   rc   rd   r  r   rH   rH   rI   unmonitor_instancesQ  s     z!EC2Connection.unmonitor_instancesc                 C   s   | j |g|dS )a  
        Deprecated Version, maintained for backward compatibility.
        Disable detailed CloudWatch monitoring for the supplied instance.

        :type instance_id: string
        :param instance_id: The instance id

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of :class:`boto.ec2.instanceinfo.InstanceInfo`
        rJ  )r  r  rH   rH   rI   unmonitor_instancee  s    z EC2Connection.unmonitor_instancec           	      C   s`   ||||d}t jdt j| jdg}| j|d< ||}||d< |rNd|d< | jd|td	d
S )a  
        Bundle Windows instance.

        :type instance_id: string
        :param instance_id: The instance id

        :type s3_bucket: string
        :param s3_bucket: The bucket in which the AMI should be stored.

        :type s3_prefix: string
        :param s3_prefix: The beginning of the file name for the AMI.

        :type s3_upload_policy: string
        :param s3_upload_policy: Base64 encoded policy that specifies condition
                                 and permissions for Amazon EC2 to upload the
                                 user's image into Amazon S3.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        )r   zStorage.S3.BucketzStorage.S3.PrefixzStorage.S3.UploadPolicyNZs3zStorage.S3.AWSAccessKeyIdz Storage.S3.UploadPolicySignaturer_   r`   ZBundleInstancerc   rd   )	rh  authZget_auth_handlerconfigZproviderr9   Zsign_stringrz   r!   )	r8   r   Z	s3_bucketZ	s3_prefixZs3_upload_policyrj   rL   Zs3auth	signaturerH   rH   rI   bundle_instancey  s$     

 zEC2Connection.bundle_instancec                 C   sJ   i }|r|  ||d |r&| || |r2d|d< | jd|dtfgddS )a  
        Retrieve current bundling tasks. If no bundle id is specified, all
        tasks are retrieved.

        :type bundle_ids: list
        :param bundle_ids: A list of strings containing identifiers for
                           previously created bundling tasks.

        :type filters: dict
        :param filters: Optional filters that can be used to limit
                        the results returned.  Filters are provided
                        in the form of a dictionary consisting of
                        filter names as the key and filter values
                        as the value.  The set of allowable filter
                        names/values is dependent on the request
                        being performed.  Check the EC2 API guide
                        for details.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        BundleIdr_   r`   ZDescribeBundleTasksrb   rc   rd   )rf   r\   rg   r!   )r8   Z
bundle_idsrW   rj   rL   rH   rH   rI   get_all_bundle_tasks  s     z"EC2Connection.get_all_bundle_tasksc                 C   s&   d|i}|rd|d< | j d|tddS )a  
        Cancel a previously submitted bundle task

        :type bundle_id: string
        :param bundle_id: The identifier of the bundle task to cancel.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        r  r_   r`   ZCancelBundleTaskrc   rd   )rz   r!   )r8   Z	bundle_idrj   rL   rH   rH   rI   cancel_bundle_task  s     z EC2Connection.cancel_bundle_taskc                 C   s,   d|i}|rd|d< | j d|tdd}|jS )aR  
        Get encrypted administrator password for a Windows instance.

        :type instance_id: string
        :param instance_id: The identifier of the instance to retrieve the
                            password for.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        r   r_   r`   ZGetPasswordDatarc   rd   )rz   r   ZpasswordData)r8   r   rj   rL   r   rH   rH   rI   get_password_data  s
    zEC2Connection.get_password_datac                 C   sJ   i }|r|  ||d |r&| || |r2d|d< | jd|dtfgddS )a  
        Get all placement groups associated with your account in a region.

        :type groupnames: list
        :param groupnames: A list of the names of placement groups to retrieve.
                           If not provided, all placement groups will be
                           returned.

        :type filters: dict
        :param filters: Optional filters that can be used to limit
                        the results returned.  Filters are provided
                        in the form of a dictionary consisting of
                        filter names as the key and filter values
                        as the value.  The set of allowable filter
                        names/values is dependent on the request
                        being performed.  Check the EC2 API guide
                        for details.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of :class:`boto.ec2.placementgroup.PlacementGroup`
        r  r_   r`   ZDescribePlacementGroupsrb   rc   rd   )rf   r\   rg   r"   )r8   r  rW   rj   rL   rH   rH   rI   get_all_placement_groups  s     z&EC2Connection.get_all_placement_groupsclusterc                 C   s*   ||d}|rd|d< | j d|dd}|S )aY  
        Create a new placement group for your account.
        This will create the placement group within the region you
        are currently connected to.

        :type name: string
        :param name: The name of the new placement group

        :type strategy: string
        :param strategy: The placement strategy of the new placement group.
                         Currently, the only acceptable value is "cluster".

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: bool
        :return: True if successful
        )r  ZStrategyr_   r`   ZCreatePlacementGrouprc   rd   r   )r8   rM   Zstrategyrj   rL   r   rH   rH   rI   create_placement_group  s
    
z$EC2Connection.create_placement_groupc                 C   s$   d|i}|rd|d< | j d|ddS )a  
        Delete a placement group from your account.

        :type key_name: string
        :param key_name: The name of the keypair to delete

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        r  r_   r`   ZDeletePlacementGrouprc   rd   r   )r8   rM   rj   rL   rH   rH   rI   delete_placement_group'  s    z$EC2Connection.delete_placement_groupc                 C   sN   t | }d}|D ]4}|| }||d| < |d k	r@||d| < |d7 }qd S )NrO   z
Tag.%d.KeyzTag.%d.Value)rd  keys)r8   rL   rK  r  rX   r   rY   rH   rH   rI   build_tag_param_list9  s    z"EC2Connection.build_tag_param_listc                 C   sH   i }|r|  || |r d|d< |dk	r0||d< | jd|dtfgddS )	a  
        Retrieve all the metadata tags associated with your account.

        :type filters: dict
        :param filters: Optional filters that can be used to limit
                        the results returned.  Filters are provided
                        in the form of a dictionary consisting of
                        filter names as the key and filter values
                        as the value.  The set of allowable filter
                        names/values is dependent on the request
                        being performed.  Check the EC2 API guide
                        for details.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :type max_results: int
        :param max_results: The maximum number of paginated instance
            items per response.

        :rtype: list
        :return: A list of :class:`boto.ec2.tag.Tag` objects
        r_   r`   Nr   ZDescribeTagsrb   rc   rd   )r\   rg   r#   )r8   rW   rj   r   rL   rH   rH   rI   get_all_tagsC  s     zEC2Connection.get_all_tagsc                 C   s:   i }|  ||d | || |r*d|d< | jd|ddS )a  
        Create new metadata tags for the specified resource ids.

        :type resource_ids: list
        :param resource_ids: List of strings

        :type tags: dict
        :param tags: A dictionary containing the name/value pairs.
                     If you want to create only a tag name, the
                     value for that tag should be the empty string
                     (e.g. '').

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        
ResourceIdr_   r`   Z
CreateTagsrc   rd   )rf   r  r   r8   Zresource_idsrK  rj   rL   rH   rH   rI   create_tagse  s    zEC2Connection.create_tagsc                 C   sP   t |tri |d}i }| ||d | || |r@d|d< | jd|ddS )a  
        Delete metadata tags for the specified resource ids.

        :type resource_ids: list
        :param resource_ids: List of strings

        :type tags: dict or list
        :param tags: Either a dictionary containing name/value pairs
                     or a list containing just tag names.
                     If you pass in a dictionary, the values must
                     match the actual tag values or the tag will
                     not be deleted.  If you pass in a value of None
                     for the tag value, all tags with that name will
                     be deleted.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        Nr  r_   r`   Z
DeleteTagsrc   rd   )rR   rV   fromkeysrf   r  r   r  rH   rH   rI   delete_tags}  s    
zEC2Connection.delete_tagsc                 C   sJ   i }|r|  ||d |r&| || |r2d|d< | jd|dtfgddS )a  
        Retrieve all of the Elastic Network Interfaces (ENI's)
        associated with your account.

        :type network_interface_ids: list
        :param network_interface_ids: a list of strings representing ENI IDs

        :type filters: dict
        :param filters: Optional filters that can be used to limit
                        the results returned.  Filters are provided
                        in the form of a dictionary consisting of
                        filter names as the key and filter values
                        as the value.  The set of allowable filter
                        names/values is dependent on the request
                        being performed.  Check the EC2 API guide
                        for details.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: list
        :return: A list of :class:`boto.ec2.networkinterface.NetworkInterface`
        r   r_   r`   ZDescribeNetworkInterfacesrb   rc   rd   )rf   r\   rg   r'   )r8   Znetwork_interface_idsrW   rj   rL   rH   rH   rI   get_all_network_interfaces  s     z(EC2Connection.get_all_network_interfacesc           	      C   s   d|i}|r||d< |r ||d< |rbg }|D ]&}t |trH||j q,|| q,| ||d |rnd|d< | jd|tdd	S )
a  
        Creates a network interface in the specified subnet.

        :type subnet_id: str
        :param subnet_id: The ID of the subnet to associate with the
            network interface.

        :type private_ip_address: str
        :param private_ip_address: The private IP address of the
            network interface.  If not supplied, one will be chosen
            for you.

        :type description: str
        :param description: The description of the network interface.

        :type groups: list
        :param groups: Lists the groups for use by the network interface.
            This can be either a list of group ID's or a list of
            :class:`boto.ec2.securitygroup.SecurityGroup` objects.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :rtype: :class:`boto.ec2.networkinterface.NetworkInterface`
        :return: The newly created network interface.
        r   r   ru   r   r_   r`   ZCreateNetworkInterfacerc   rd   )rR   r   r   r   rf   rz   r'   )	r8   r   r   r{   r   rj   rL   idsr   rH   rH   rI   create_network_interface  s$    
 z&EC2Connection.create_network_interfacec                 C   s(   |||d}|rd|d< | j d|ddS )aJ  
        Attaches a network interface to an instance.

        :type network_interface_id: str
        :param network_interface_id: The ID of the network interface to attach.

        :type instance_id: str
        :param instance_id: The ID of the instance that will be attached
            to the network interface.

        :type device_index: int
        :param device_index: The index of the device for the network
            interface attachment on the instance.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        )r   r   ZDeviceIndexr_   r`   ZAttachNetworkInterfacerc   rd   r   )r8   r  r   Zdevice_indexrj   rL   rH   rH   rI   attach_network_interface  s    z&EC2Connection.attach_network_interfacec                 C   s0   d|i}|rd|d< |r d|d< | j d|ddS )aZ  
        Detaches a network interface from an instance.

        :type attachment_id: str
        :param attachment_id: The ID of the attachment.

        :type force: bool
        :param force: Set to true to force a detachment.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        ZAttachmentIdr_   r   r`   ZDetachNetworkInterfacerc   rd   r   )r8   r   r   rj   rL   rH   rH   rI   detach_network_interface  s    z&EC2Connection.detach_network_interfacec                 C   s$   d|i}|rd|d< | j d|ddS )a  
        Delete the specified network interface.

        :type network_interface_id: str
        :param network_interface_id: The ID of the network interface to delete.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        r   r_   r`   ZDeleteNetworkInterfacerc   rd   r   )r8   r  rj   rL   rH   rH   rI   delete_network_interface  s    z&EC2Connection.delete_network_interfacec                 C   s   i }| j d|dtfgddS )z
        Get all instance_types available on this cloud (eucalyptus specific)

        :rtype: list of :class:`boto.ec2.instancetype.InstanceType`
        :return: The requested InstanceType objects
        ZDescribeInstanceTypesrb   rc   rd   )rg   r$   )r8   rL   rH   rH   rI   get_all_instance_types-  s    z$EC2Connection.get_all_instance_typesc	           
      C   s   ||d}	|dk	r||	d< |dk	r*||	d< |dk	r:||	d< |dk	rR|rJdnd|	d< |dk	rb||	d	< |rnd|	d
< | j d|	tddS )z
        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.
        :rtype: :class:`boto.ec2.image.CopyImage`
        :return: Object containing the image_id of the copied image.
        )rO  ZSourceImageIdNrt   ru   r   r_   r   r9  r:  r`   r	   rc   rd   )rz   r	   )
r8   rP  Zsource_image_idrM   r{   r   rj   r?  r@  rL   rH   rH   rI   
copy_image7  s$    

zEC2Connection.copy_imagec                 C   s>   i }|dk	r|  ||d |r&d|d< | jd|dtfgddS )	r   NZAttributeNamer_   r`   ZDescribeAccountAttributesrb   rc   rd   )rf   rg   r(   )r8   Zattribute_namesrj   rL   rH   rH   rI   describe_account_attributesS  s     z)EC2Connection.describe_account_attributesc                 C   s6   d|i}|dk	r||d< |r$d|d< | j d|tddS )	r   r  Nr   r_   r`   ZDescribeVpcAttributerc   rd   )rz   r)   )r8   r  r   rj   rL   rH   rH   rI   describe_vpc_attributea  s      z$EC2Connection.describe_vpc_attributec                 C   sT   d|i}|dk	r |rdnd|d< |dk	r8|r0dnd|d< |rDd|d< | j d|d	d
S )r   r  Nr_   r   zEnableDnsSupport.ValuezEnableDnsHostnames.Valuer`   ZModifyVpcAttributerc   rd   r   )r8   r  Zenable_dns_supportZenable_dns_hostnamesrj   rL   rH   rH   rI   modify_vpc_attributeq  s     

z"EC2Connection.modify_vpc_attributec                 C   sf   i }|r|  ||d |r&| || |r2d|d< |dk	rB||d< |rN||d< | jd|dtfgd	d
S )aG  
        Get all of your linked EC2-Classic instances. This request only
        returns information about EC2-Classic instances linked  to
        a VPC through ClassicLink

        :type instance_ids: list
        :param instance_ids: A list of strings of instance IDs. Must be
            instances linked to a VPC through ClassicLink.

        :type filters: dict
        :param filters: Optional filters that can be used to limit the
            results returned.  Filters are provided in the form of a
            dictionary consisting of filter names as the key and
            filter values as the value.  The set of allowable filter
            names/values is dependent on the request being performed.
            Check the EC2 API guide for details.

        :type dry_run: bool
        :param dry_run: Set to True if the operation should not actually run.

        :type max_results: int
        :param max_results: The maximum number of paginated instance
            items per response.

        :rtype: list
        :return: A list of  :class:`boto.ec2.instance.Instance`
        r   r_   r`   Nr   r   ZDescribeClassicLinkInstancesrb   rc   rd   )rf   r\   rg   r   )r8   r   rW   rj   r   r   rL   rH   rH   rI   get_all_classic_link_instances  s     z,EC2Connection.get_all_classic_link_instances)NNTNNNNNNr   NNr/   NNTN)NNNNF)NNF)NNF)F)NNNNNNNNFNNNF)FF)NFNF)r   F)r   r   NNNF)r   F)NNFN)NNFN)NNFNN)NNNNFF)rO   rO   NNNNr   NNNFNNFNNNNNNNNNFNF)NF)NFF)NF)F)NF)F)F)NF)F)F)NNF)	NNNNNFNNN)rO   r  NNNNNNNNr   NNNFNNNNNNFNF)F)F)F)F)NNF)NNNF)NF)NNNFF)NNNNNFF)NNNNNFF)NNNNNFF)NNF)NNF)NNF)NNF)NNNNF)F)r3  F)F)NNNFNF)F)F)NNFF)NNNNF)NF)F)NF)rR  rS  rT  T)rq  F)rq  r   NNF)rq  F)NNF)F)F)F)F)NNNF)NF)NNF)NNNNNNF)
NNNNNNNNNF)NNNNF)NNNNNNF)
NNNNNNNNNF)NNNNF)NNF)NNNNNNNNNNNNNF)NNF)rO   NF)F)NF)NNN)F)F)F)F)F)NNF)F)F)NNF)r  F)F)NFN)F)F)NNF)NNNF)F)FF)F)NNNFNN)NF)NF)NNF)NNFNN)|__name__
__module____qualname__rh  r  r   r7   r2   r3   r,   rx  r6   rJ   rN   r\   rk   ro   rp   rs   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  r  r  r  r  r#  r'  r(  r)  r*  r+  r.  r/  r2  r4  r6  rA  rB  rE  rF  rH  rN  r   rQ  rp  rs  rt  ru  rw  r|  r~  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  __classcell__rH   rH   rF   rI   r.   I   s:  
                               
.


               
a
$      
1 
        
, 
 
)   
,     
4       
7                                 
 r
)  
I
B   
)          
P                              
 `%   
*     
4       
       
0       
0 
 
'   
%#      
/  

       
9     
-      
6  
'   
  
      
) 
 ,   
* 
(        
;           
b    
'        
A             
Y     
@)             
z   
%   
*
G 
%   
*
( 
" 
$
""     
/
 

        
   
    r.   )M__doc__r   r   r   r   rh  Z	boto.authr   Zboto.connectionr   Zboto.resultsetr   Zboto.ec2.imager   r   r	   Zboto.ec2.instancer
   r   r   r   Zboto.ec2.keypairr   Zboto.ec2.addressr   Zboto.ec2.volumer   r   Zboto.ec2.snapshotr   r   Zboto.ec2.zoner   Zboto.ec2.securitygroupr   Zboto.ec2.regioninfor   Zboto.ec2.instanceinfor   Zboto.ec2.reservedinstancer   r   r   r   r   r   Zboto.ec2.spotinstancerequestr   Zboto.ec2.spotpricehistoryr   Z!boto.ec2.spotdatafeedsubscriptionr    Zboto.ec2.bundleinstancer!   Zboto.ec2.placementgroupr"   Zboto.ec2.tagr#   Zboto.ec2.instancetyper$   Zboto.ec2.instancestatusr%   Zboto.ec2.volumestatusr&   Zboto.ec2.networkinterfacer'   Zboto.ec2.attributesr(   r)   Zboto.ec2.blockdevicemappingr*   r+   Zboto.exceptionr,   Zboto.compatr-   r.   rH   rH   rH   rI   <module>   sR   