
    Vh-                     p   d Z dZdZddlZddlmZ ddlmZ ddlmZ ddlm	Z	 dd	lm
Z
 dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ  G d de      Zd Zd Zd Zd#dZ	 	 	 	 	 	 	 	 d$dZ G d d      Z G d d      Z  G d d       Z!d! Z"e#d"k(  r e"        yy)%a  
---
module: ec2_ami
version_added: 1.0.0
short_description: Create or destroy an image (AMI) in EC2
description:
   - Registers or deregisters EC2 images.
options:
  instance_id:
    description:
      - Instance ID to create the AMI from.
    type: str
  name:
    description:
      - The name of the new AMI.
    type: str
  architecture:
    description:
      - The target architecture of the image to register.
    default: "x86_64"
    type: str
  kernel_id:
    description:
      - The target kernel id of the image to register.
    type: str
  virtualization_type:
    description:
      - The virtualization type of the image to register.
    default: "hvm"
    type: str
  root_device_name:
    description:
      - The root device name of the image to register.
    type: str
  wait:
    description:
      - Wait for the AMI to be in state 'available' before returning.
    default: false
    type: bool
  wait_timeout:
    description:
      - How long before wait gives up, in seconds.
    default: 1200
    type: int
  state:
    description:
      - Register or deregister an AMI.
    default: 'present'
    choices: [ "absent", "present" ]
    type: str
  description:
    description:
      - Human-readable string describing the contents and purpose of the AMI.
    type: str
    default: ''
  no_reboot:
    description:
      - Flag indicating that the bundling process should not attempt to shutdown the instance before bundling. If this flag is V(true), the
        responsibility of maintaining file system integrity is left to the owner of the instance.
    default: false
    type: bool
  image_id:
    description:
      - Image ID to be deregistered.
    type: str
  device_mapping:
    description:
      - List of device hashes/dictionaries with custom configurations (same block-device-mapping parameters).
    type: list
    elements: dict
    suboptions:
      device_name:
        type: str
        description:
          - The device name. For example V(/dev/sda).
        required: true
      virtual_name:
        type: str
        description:
          - The virtual name for the device.
          - See the AWS documentation for more detail U(https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_BlockDeviceMapping.html).
      no_device:
        type: bool
        description:
          - Suppresses the specified device included in the block device mapping of the AMI.
      volume_type:
        type: str
        description: The volume type. Defaults to V(gp2) when not set.
      delete_on_termination:
        type: bool
        description: Whether the device should be automatically deleted when the Instance is terminated.
      snapshot_id:
        type: str
        description: The ID of the Snapshot.
      iops:
        type: int
        description: When using O(device_mapping.volume_type=io1), this sets the number of IOPS provisioned for the volume.
      encrypted:
        type: bool
        description: Whether the volume should be encrypted.
      volume_size:
        aliases: ['size']
        type: int
        description: The size of the volume (in GiB).
  delete_snapshot:
    description:
      - Delete snapshots when deregistering the AMI.
    default: false
    type: bool
  launch_permissions:
    description:
      - Launch permissions for the AMI.
      - You must pass all desired launch permissions if you wish to modify existing launch permissions (passing just groups will remove all users).
    required: false
    type: dict
    suboptions:
      user_ids:
        description: List of account IDs.
        type: list
        elements: str
        required: false
      group_names:
        description: List of group names.
        type: list
        elements: str
        required: false
      org_arns:
        description: List of The Amazon Resource Name(s) (ARN) of organization(s).
        type: list
        elements: str
        required: false
        version_added: 6.5.0
      org_unit_arns:
        description: List of The Amazon Resource Name(s) (ARN) of an organizational unit(s) (OU).
        type: list
        elements: str
        required: false
        version_added: 6.5.0
  image_location:
    description:
      - The S3 location of an image to use for the AMI.
    type: str
  enhanced_networking:
    description:
      - A boolean representing whether enhanced networking with ENA is enabled or not.
    type: bool
  billing_products:
    description:
      - A list of valid billing codes. To be used with valid accounts by AWS Marketplace vendors.
    type: list
    elements: str
  ramdisk_id:
    description:
      - The ID of the RAM disk.
    type: str
  sriov_net_support:
    description:
      - Set to simple to enable enhanced networking with the Intel 82599 Virtual Function interface for the AMI and any instances that you launch from the AMI.
    type: str
  boot_mode:
    description:
      - The boot mode of the AMI.
      - See the AWS documentation for more detail U(https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ami-boot.html).
      - Support for V(uefi-preferred) was added in release 8.2.0.
    type: str
    choices: ['legacy-bios', 'uefi', 'uefi-preferred']
    version_added: 5.5.0
  tpm_support:
    description:
      - Set to V(v2.0) to enable Trusted Platform Module (TPM) support.
      - If the image is configured for NitroTPM support, the value is V(v2.0).
      - Requires O(boot_mode) to be set to V(uefi).
      - Requires an instance type that is compatible with Nitro.
      - See the AWS documentation for more detail U(https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/nitrotpm.html).
    type: str
    version_added: 5.5.0
  uefi_data:
    description:
      - Base64 representation of the non-volatile UEFI variable store.
      - See the AWS documentation for more detail U(https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/uefi-secure-boot.html).
    type: str
    version_added: 5.5.0
author:
  - "Evan Duffield (@scicoin-project) <eduffield@iacquire.com>"
  - "Constantin Bugneac (@Constantin07) <constantin.bugneac@endava.com>"
  - "Ross Williams (@gunzy83) <gunzy83au@gmail.com>"
  - "Willem van Ketwich (@wilvk) <willvk@gmail.com>"
extends_documentation_fragment:
  - amazon.aws.common.modules
  - amazon.aws.region.modules
  - amazon.aws.tags
  - amazon.aws.boto3
ao  
# Note: These examples do not set authentication details, see the AWS Guide for details.

- name: Basic AMI Creation
  amazon.aws.ec2_ami:
    instance_id: i-xxxxxx
    wait: true
    name: newtest
    tags:
      Name: newtest
      Service: TestService

- name: Basic AMI Creation, without waiting
  amazon.aws.ec2_ami:
    instance_id: i-xxxxxx
    wait: false
    name: newtest

- name: AMI Registration from EBS Snapshot
  amazon.aws.ec2_ami:
    name: newtest
    state: present
    architecture: x86_64
    virtualization_type: hvm
    root_device_name: /dev/xvda
    device_mapping:
      - device_name: /dev/xvda
        volume_size: 8
        snapshot_id: snap-xxxxxxxx
        delete_on_termination: true
        volume_type: gp2

- name: AMI Creation, with a custom root-device size and another EBS attached
  amazon.aws.ec2_ami:
    instance_id: i-xxxxxx
    name: newtest
    device_mapping:
      - device_name: /dev/sda1
        size: XXX
        delete_on_termination: true
        volume_type: gp2
      - device_name: /dev/sdb
        size: YYY
        delete_on_termination: false
        volume_type: gp2

- name: AMI Creation, excluding a volume attached at /dev/sdb
  amazon.aws.ec2_ami:
    instance_id: i-xxxxxx
    name: newtest
    device_mapping:
      - device_name: /dev/sda1
        size: XXX
        delete_on_termination: true
        volume_type: gp2
      - device_name: /dev/sdb
        no_device: true

- name: AMI Creation with boot_mode and tpm_support
  amazon.aws.ec2_ami:
    name: newtest
    state: present
    architecture: x86_64
    virtualization_type: hvm
    root_device_name: /dev/sda1
    device_mapping:
      - device_name: /dev/sda1
        snapshot_id: "{{ snapshot_id }}"
    wait: true
    region: us-east-1
    boot_mode: uefi
    uefi_data: data_file.bin
    tpm_support: v2.0

- name: Deregister/Delete AMI (keep associated snapshots)
  amazon.aws.ec2_ami:
    image_id: "{{ instance.image_id }}"
    delete_snapshot: false
    state: absent

- name: Deregister AMI (delete associated snapshots too)
  amazon.aws.ec2_ami:
    image_id: "{{ instance.image_id }}"
    delete_snapshot: true
    state: absent

- name: Update AMI Launch Permissions, making it public
  amazon.aws.ec2_ami:
    image_id: "{{ instance.image_id }}"
    state: present
    launch_permissions:
      group_names: ['all']

- name: Allow AMI to be launched by another account
  amazon.aws.ec2_ami:
    image_id: "{{ instance.image_id }}"
    state: present
    launch_permissions:
      user_ids: ['123456789012']

- name: Update AMI Launch Permissions, share AMI across an Organization and Organizational Units
  amazon.aws.ec2_ami:
    image_id: "{{ instance.image_id }}"
    state: present
    launch_permissions:
      org_arns: ['arn:aws:organizations::123456789012:organization/o-123ab4cdef']
      org_unit_arns: ['arn:aws:organizations::123456789012:ou/o-123example/ou-1234-5example']
a  
architecture:
    description: Architecture of image.
    returned: when AMI is created or already exists
    type: str
    sample: "x86_64"
block_device_mapping:
    description: Block device mapping associated with image.
    returned: when AMI is created or already exists
    type: dict
    sample: {
        "/dev/sda1": {
            "delete_on_termination": true,
            "encrypted": false,
            "size": 10,
            "snapshot_id": "snap-1a03b80e7",
            "volume_type": "standard"
        }
    }
creationDate:
    description: Creation date of image.
    returned: when AMI is created or already exists
    type: str
    sample: "2015-10-15T22:43:44.000Z"
description:
    description: Description of image.
    returned: when AMI is created or already exists
    type: str
    sample: "nat-server"
enhanced_networking:
    description: Specifies whether enhanced networking with ENA is enabled.
    returned: when AMI is created or already exists
    type: bool
    sample: true
hypervisor:
    description: Type of hypervisor.
    returned: when AMI is created or already exists
    type: str
    sample: "xen"
image_id:
    description: ID of the image.
    returned: when AMI is created or already exists
    type: str
    sample: "ami-1234abcd"
image_owner_alias:
    description: The owner alias ( amazon | aws-marketplace).
    returned: when AMI is created or already exists
    type: str
    sample: "amazon"
image_type:
    description: Type of image.
    returned: when AMI is created or already exists
    type: str
    sample: "machine"
is_public:
    description: Whether image is public.
    returned: when AMI is created or already exists
    type: bool
    sample: false
kernel_id:
    description: The kernel associated with the image, if any. Only applicable for machine images.
    returned: when AMI is created or already exists
    type: str
    sample: "aki-88aa75e1"
launch_permission:
    description: Permissions allowing other accounts to access the AMI.
    returned: when AMI is created or already exists
    type: list
    sample:
      - group: "all"
location:
    description: Location of image.
    returned: when AMI is created or already exists
    type: str
    sample: "123456789012/nat-server"
name:
    description: AMI name of image.
    returned: when AMI is created or already exists
    type: str
    sample: "nat-server"
ownerId:
    description: Owner of image.
    returned: when AMI is created or already exists
    type: str
    sample: "123456789012"
platform:
    description: Platform of image.
    returned: when AMI is created or already exists
    type: str
    sample: "Windows"
product_codes:
    description: Any product codes associated with the AMI.
    returned: when AMI is created or already exists
    type: list
    sample: []
ramdisk_id:
    description: The RAM disk associated with the image, if any. Only applicable for machine images.
    returned: when AMI is created or already exists
    type: str
    sample: null
root_device_name:
    description: Root device name of image.
    returned: when AMI is created or already exists
    type: str
    sample: "/dev/sda1"
root_device_type:
    description: Root device type of image.
    returned: when AMI is created or already exists
    type: str
    sample: "ebs"
sriov_net_support:
    description: Specifies whether enhanced networking with the Intel 82599 Virtual Function interface is enabled.
    returned: when AMI is created or already exists
    type: str
    sample: "simple"
state:
    description: State of image.
    returned: when AMI is created or already exists
    type: str
    sample: "available"
state_reason:
    description: The reason for the state change.
    returned: when AMI is created or already exists
    type: dict
    sample: {
                'Code': 'string',
                'Message': 'string'
            }
tags:
    description: A dictionary of tags assigned to image.
    returned: when AMI is created or already exists
    type: dict
    sample: {
        "Env": "devel",
        "Name": "nat-server"
    }
virtualization_type:
    description: Image virtualization type.
    returned: when AMI is created or already exists
    type: str
    sample: "hvm"
snapshots_deleted:
    description: A list of snapshot ids deleted after deregistering image.
    returned: after AMI is deregistered, if I(delete_snapshot=true)
    type: list
    sample: [
        "snap-fbcccb8f",
        "snap-cfe7cdb4"
    ]
    N)camel_dict_to_snake_dict)AnsibleEC2Error)add_ec2_tags)create_image)delete_snapshot)deregister_image)describe_image_attribute)describe_imagesensure_ec2_tags)modify_image_attribute)register_image)AnsibleAWSModule)boto3_tag_list_to_ansible_dict)boto3_tag_specifications)wait_for_resource_statec                         e Zd Zd fd	Z xZS )Ec2AmiFailurec                 @    t         |   |       || _        || _        y N)super__init__
original_emessage)selfr   r   	__class__s      f/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/amazon/aws/plugins/modules/ec2_ami.pyr   zEc2AmiFailure.__init__  s    !$    NN)__name__
__module____qualname__r   __classcell__)r   s   @r   r   r     s     r   r   c                    i }| | j                  d      | j                  d      }|D ]  }|j                  d      }d|v re|j                  d      }|j                  d      |j                  d      |j                  d      |j                  d      |j                  d      d	}nd
|v rt        |d
         }||<    |S )Nblock_device_mappingsdevice_nameebsvolume_sizesnapshot_idvolume_type	encrypteddelete_on_termination)sizer)   r*   r+   r,   virtual_name)r.   )getdict)imagebdm_dictbdmdevicer&   r'   bdm_dict_items          r   get_block_device_mappingr6     s    HUYY'>?Kii/0 	2F **]3Kjj'GGM2#&77=#9#&77=#9!$!5-0WW5L-M!  6) $&2H I$1H[!	2 Or   c           
         t        |       }t        di d|j                  d      d|j                  d      d|j                  d      dt        |      d|j                  d      d|j                  d      d|j                  d      d	|j                  d
      d|j                  d      d|j                  d      d|j                  d      d|j                  d      d|j                  d      d|j                  d      dt	        |j                  d            d|j                  d      d|j                  d      d|j                  d      d|j                  d      d|j                  d      d|j                  d      d|j                  d      d|j                  d      d|j                  d      d|j                  d      S ) Nimage_idstatearchitectureblock_device_mappingcreationDatecreation_datedescription
hypervisor	is_publicpubliclocationimage_locationownerIdowner_idroot_device_nameroot_device_typevirtualization_typenametagsplatformenhanced_networkingena_supportimage_owner_alias
image_type	kernel_idproduct_codes
ramdisk_idsriov_net_supportstate_reasonlaunch_permissions )r   r0   r/   r6   r   )camel_imager1   s     r   get_ami_inforX     s   $[1E :&ii  YY~. 6e<	
 YY/ IIm, 99\* ))H% +, 		*% #56 #56 "II&;< YYv ,EIIf,=>  :&!" "IIm4#$  ))$78%& 99\*'( ))K()* ii0+, 99\*-.  ))$78/0 YY~.12 !99%9:3 r   c                    	 t        | |g      }t        |      dk(  ry t        |      dkD  r$t        dt	        t        |             d| d      |d   }	 t        | d|	      }|r|d
   |d
<   t        | d|	      }|r|d   |d<   |S # t        $ r}t        d|      d }~ww xY w# t        $ r}t        d| |      d }~ww xY w)N)ImageIdsz"Error retrieving image by image_idr      zInvalid number of instances (z) found for image_id: .launchPermission)	attributer8   LaunchPermissionsproductCodesProductCodesz,Error retrieving image attributes for image )r
   r   r   lenstrr	   )
connectionr8   imageseresultimage_attribues         r   get_image_by_idri     s   E xjA 6{a
6{Q;CF<L;MMcdlcmmnoppAYFZ1*HZemn*89L*MF&'1*aij%3N%CF>" M'  E@!DDE"  ZJ8*UWXYYZs/   B	 0B& 		B#BB#&	C/B>>Cc                     | j                  |      }|+| ||      }||| |<   n|| |   |<   | j                  |       | S r   )r/   pop)dict_objectr^   new_attribute
child_nodeattribute_typenew_items         r   rename_item_if_existsrq   7  sW    y)H%%h/H)1K&5=K
#M2	"r   c	                     |s|s| j                  d       |r|dk7  r| j                  d       |dk(  r|s|s|s| j                  d       y y y y y )Nz0one of the following is required: name, image_iduefiz5To specify 'tpm_support', 'boot_mode' must be 'uefi'.presentzgThe parameters instance_id or device_mapping (register from EBS snapshot) are required for a new image.)	fail_json)
moduler8   instance_idrI   r9   tpm_support	uefi_data	boot_modedevice_mapping_s
             r   validate_paramsr}   D  s^     KLyF*PQ	(K>u	
 DRK(r   c                   L    e Zd Zed        Zed        Zed        Zed        Zy)DeregisterImagec                     t        ||      }|| j                  d       d|v r| j                  dd       y | j                  d| dd	       y )
NFchangedImageIdTz1Would have deregistered AMI if not in check mode.r   msgImage  has already been deregistered.r   r   )ri   	exit_json)rv   rd   r8   r1   s       r   do_check_modezDeregisterImage.do_check_mode_  s^    
H5=U+T/bc6(3R!S]bcr   c                       fd}|S )Nc              3      K   	 j                  d      xs g D ]6  }|j                  di       j                  d      }|'t        | |       | 8 y # t        $ r}t        d|      d }~ww xY ww)NBlockDeviceMappingsEbs
SnapshotIdzFailed to delete snapshot.)r/   r   r   r   )rd   mappingr)   rf   r1   s       r   purge_snapshotsz>DeregisterImage.defer_purge_snapshots.<locals>.purge_snapshotsm  s     E$yy)>?E2 &G")++eR"8"<"<\"JK"* #J<%%& # E#$@!DDEs)   A1AA A1	A.A))A..A1rV   )r1   r   s   ` r   defer_purge_snapshotsz%DeregisterImage.defer_purge_snapshotsk  s    		E r   c                 6   t        | |      }t        j                         |z   }|t        j                         kD  r=|;t        | |      }t        j                  d       |t        j                         kD  r|;|t        j                         k  rt        d      y )N   z/Timed out waiting for image to be deregistered.)ri   timesleepr   )rd   r8   wait_timeoutr1   	wait_tills        r   timeoutzDeregisterImage.timeoutz  s~    
H5IIK,.	$))+%%*;#J9EJJqM $))+%%*; 		# QRR $r   c                    |j                   j                  d      }|j                   j                  d      }t        ||      }||j                  d       | j	                  |      }d|v r	 t        ||       n|j                  d| d	d
       |r| j                  |||       ddd
}	|j                   j                  d      rt         ||            |	d<    |j                  di |	 y# t        $ r}t        d|      d}~ww xY w)z"Entry point to deregister an imagewaitr   NFr   r   zError deregistering imager   r   r   z"AMI deregister operation complete.Tr   snapshots_deletedrV   )
paramsr/   ri   r   r   r   r   r   r   list)
clsrv   rd   r8   r   r   r1   r   rf   exit_paramss
             r   dozDeregisterImage.do  s    }}  (}}((8
H5=U+ 33E: D X6 6(3R!S]bcKK
Hl;BtT==.//3OJ4O/PK+,';' # D#$?CCDs   -C- -	D6DDN)	r    r!   r"   staticmethodr   r   r   classmethodr   rV   r   r   r   r   ^  sT    	d 	d   	S 	S ( (r   r   c                   L    e Zd Zed        Zed        Zed        Zed        Zy)UpdateImagec           	         |y|d   }t        d |D              }t        d |j                  dg       D              }t        d |D              }t        |j                  dg             }t        d |D              }	t        d	 |j                  d
g       D              }
t        d |D              }t        d |j                  dg       D              }||z
  }||z
  }||z
  }||z
  }|
|	z
  }|	|
z
  }||z
  }||z
  }t        |      D cg c]  }t        |       c}t        |      D cg c]  }t        |       c}z   t        |      D cg c]  }t        |       c}z   t        |      D cg c]  }t        |       c}z   }t        |      D cg c]  }t        |       c}t        |      D cg c]  }t        |       c}z   t        |      D cg c]  }t        |       c}z   t        |      D cg c]  }t        |       c}z   }|s|sy	 |st	        | |d   dt        ||            }d}|S c c}w c c}w c c}w c c}w c c}w c c}w c c}w c c}w # t
        $ r}t        d|d    |      d }~ww xY w)NFr_   c              3   0   K   | ]  }d |v s|d      yw)UserIdNrV   .0
permissions     r   	<genexpr>z4UpdateImage.set_launch_permission.<locals>.<genexpr>  s     qZZbfpZpJx0q   	
c              3   2   K   | ]  }t        |        y wr   rc   )r   user_ids     r   r   z4UpdateImage.set_launch_permission.<locals>.<genexpr>  s     _WCL_   user_idsc              3   0   K   | ]  }d |v s|d      yw)GroupNrV   r   s     r   r   z4UpdateImage.set_launch_permission.<locals>.<genexpr>  s     pZZaeoZoZ0pr   group_namesc              3   0   K   | ]  }d |v s|d      yw)OrganizationArnNrV   r   s     r   r   z4UpdateImage.set_launch_permission.<locals>.<genexpr>  s$      
.8SdhrSrJ()
r   c              3   2   K   | ]  }t        |        y wr   r   )r   org_arns     r   r   z4UpdateImage.set_launch_permission.<locals>.<genexpr>  s     bs7|br   org_arnsc              3   .   K   | ]  }d |v r|d      yw)OrganizationalUnitArnNrV   r   s     r   r   z4UpdateImage.set_launch_permission.<locals>.<genexpr>  s&      $
&*4 ./$
s   c              3   2   K   | ]  }t        |        y wr   r   )r   org_unit_arns     r   r   z4UpdateImage.set_launch_permission.<locals>.<genexpr>  s     #v,C$5#vr   org_unit_arnsr   r   r   r   r   r]   )AddRemove)r8   	AttributeLaunchPermissionTz+Error updating launch permissions of image )setr/   sortedr0   r   r   r   )rd   r1   rU   
check_modecurrent_permissionscurrent_usersdesired_userscurrent_groupsdesired_groupscurrent_org_arnsdesired_org_arnscurrent_org_unit_arnsdesired_org_unit_arnsto_add_usersto_remove_usersto_add_groupsto_remove_groupsto_add_org_arnsto_remove_org_arnsto_add_org_unit_arnsto_remove_org_unit_arnsgroupr   r   r   to_add	to_remover   rf   s                                r   set_launch_permissionz!UpdateImage.set_launch_permission  s   %#$78qCVqq_8J8N8Nz[]8^__pCVpp/33M2FG 
<O
 
 b;M;Q;QR\^`;abb # $
1$
 !

 !$#vJ\J`J`aprtJu#v v$}4'-7&7)N:*-==-0@@47LL"7:O"O -3=,AB5TB39,3GHt7#HI<B?<STtG,TU MSSgLhiLt,7ij 	 -33C,DE5TE39/3JKt7#KL<BCU<VWtG,WX MSSjLklLt,7lm 	 )
	e0"9-0%)fY%G	 G 7 CHTi FKWl  	e"MeT]N^M_ `bcdd	esH   I)II1II8II I$!I) )	J	2JJ	c                 (    |syt        | ||||      S )NF)rJ   
purge_tagsr   )rd   rv   r8   rJ   r   s        r   set_tagszUpdateImage.set_tags  s    z68$S]^^r   c                     |sy||d   k(  ry	 |j                   st        | |d   dd|i       y# t        $ r}t        d|d    |      d }~ww xY w)NFDescriptionr   Value)r8   r   r   Tz$Error setting description for image )r   r   r   r   )rd   rv   r1   r>   rf   s        r   set_descriptionzUpdateImage.set_description  sx    %..
	^$$&"9-+!(+ 6	  	^"FuYGWFX Y[\]]	^s    / 	AA

Ac           
         |j                   j                  d      }|r&|j                         D ci c]  \  }}|	|| }}}t        ||      }|t	        d| d      d}|| j                  ||||j                        z  }|| j                  ||||j                   d   |j                   d         z  }|| j                  ||||j                   d         z  }|r |j                  r|j                  d	d
       y|r) |j                  ddd	dt        t        ||             y |j                  ddddt        |       yc c}}w )zEntry point to update an imagerU   Nr   z does not existFrJ   r   r>   Tz,Would have updated AMI if not in check mode.r   zAMI updated.r   zAMI not updated.rV   )r   r/   itemsri   r   r   r   r   r   r   rX   )	r   rv   rd   r8   rU   kvr1   r   s	            r   r   zUpdateImage.do   s\    $]]../CD3E3K3K3M!_41aQRQ^!Q$!_!_
H5=&
/ BCC3,,Z@RTZTeTeff3<<
FHfmmF>SU[UbUbcoUpqq3&&z65&--P]B^__v((T/]^Fuuo^hjrNsAtuFZ!3UZlSXFYZ! "`s
   
EEN)	r    r!   r"   r   r   r   r   r   r   rV   r   r   r   r     sW    : :x _ _ ^ ^& [ [r   r   c                       e Zd Zed        Zed        Zed        Zed        Zed        Zed        Z	ed        Z
ed        Zy	)
CreateImagec                     t        |dt        | j                  d         gdg      }|s| j                  dd       y | j                  dd       y )	NrI   )NameValues)FiltersTz.Would have created a AMI if not in check mode.r   FzBError registering image: AMI name is already in use by another AMI)r
   rc   r   r   )rv   rd   	_image_idre   s       r   r   zCreateImage.do_check_mode  sW     vRUV\VcVcdjVkRlQm6n5opT/_`U0tur   c                     |j                   j                  d      rO|j                   j                  d      r3d}|j                   j                  d      |z  }t        | |d|||g       y y y )Nr   r      image_available)delaymax_attemptsrZ   )r   r/   r   )rd   rv   r8   r   r   s        r   r   zCreateImage.wait"  sg    ==V$):):>)JE!==,,^<EL#F$5UQ]iqhr *K$r   c                    |sy t        | |      }t        | |||j                  d          |rZ|j                  d      rH|j                  d      D ]3  }d|vrt        | ||j                  d      j                  d      |       5 y y y )NrJ   r   r   r   )ri   r   r   r/   )rd   rv   rJ   r8   
image_infor   s         r   r   zCreateImage.set_tags+  s    $Z:
Z6==3HI*..)>?%>>*?@ ]'ZU1C1G1G1UW[\	] @:r   c                    |sy |j                         D ci c]  \  }}|	|| }}}	 ddg id}|j                  dg       D ]#  }|d   d   j                  t        |             % |j                  dg       D ],  }|d   d   j                  t        t	        |                   . |j                  dg       D ]#  }|d   d   j                  t        |	             % |j                  d
g       D ]#  }	|d   d   j                  t        |	             % |d   d   rt        | fd|i| y y c c}}w # t        $ r}
t        d| |
      d }
~
ww xY w)Nr   r   )r   r   r   r   r   r   r   r   r   r   r8   z+Error setting launch permissions for image )r   r/   appendr0   rc   r   r   r   )rd   rU   r8   r   r   r   
group_namer   r   r   rf   s              r   set_launch_permissionsz"CreateImage.set_launch_permissions9  s   !/A/G/G/I[tq!Q]ad[[	]#5ESU;WF044]BG Q
)*5188J9OPQ-11*bA T)*5188S\9RST-11*bA X)*5188g9VWX 2 6 6 K c)*5188T`9abc()%0&zOHOO 1 \  	]"MhZ XZ[\\	]s"   
D3D3DD9 9	EEEc                 .    d| v }|rt         }|S t        }|S )N
InstanceId)r   r   )create_image_parameterscreate_from_instancefuncs      r   create_or_registerzCreateImage.create_or_registerN  s'    +/FF3| :Hr   c                    g }| D ]  }|j                         D ci c]  \  }}|	|| }}}i |d<   t        |ddd       t        |dd       t        |ddd       t        |dd	d       t        |d
d       t        |dddt               t        |ddd       t        |dd       t        |dddt               t        |ddd       d|v r|d   du rd|d<   n|d= |j                  |        |S c c}}w )Nr   r,   DeleteOnTerminationr&   
DeviceNamer+   	EncryptediopsIops	no_deviceNoDevicer-   
VolumeSize)ro   r)   r   r.   VirtualNamer(   r*   
VolumeTypeT )r   rq   intr   )r{   r;   r4   r   r   s        r   build_block_device_mappingz&CreateImage.build_block_device_mappingT  s     "$ 	0F'-||~Gtq!adGFGF5M!&*ACXZ_`!&-F!&+{EJ!&&&%@!&+zB!&&,VYZ!&-uM!&.-H!&-u]`a!&-uM V#*%-)+F:&z* ''/+	0, $#+ Hs
   
C1C1c                     | j                  d      }| j                  d      }| j                  d      }| j                  d      }| j                  d      xs g }| j                  d      }| j                  d      }| j                  d      }| j                  d	      }	| j                  d
      }
| j                  d      }| j                  d      }| j                  d      }| j                  d      }| j                  d      }| j                  d      }| j                  d      }| j                  d      }|
|t        j                  |      d}|r#|j                  ||t	        |ddg      d       n|j                  ||||||	||||||d       |j                         D ci c]  \  }}|s	|| c}}S c c}}w )Nr:   billing_productsrz   r>   r{   rL   rC   rw   rP   rI   	no_rebootrR   rF   rS   rJ   rx   ry   rH   )r   r   r   r1   snapshot)types)r   NoRebootTagSpecifications)ArchitectureBillingProductsBootMode
EnaSupportImageLocationKernelId	RamdiskIdRootDeviceNameSriovNetSupport
TpmSupportUefiDataVirtualizationType)r/   r   r  updater   r   )kwargsr:   r  rz   r>   r{   rL   rC   rw   rP   rI   r  rR   rF   rS   rJ   rx   ry   rH   r   r   r   s                         r   build_create_image_parametersz)CreateImage.build_create_image_parametersp  s   zz.1!::&89JJ{+	jj/$45;$jj)>?$45jj/JJ{+	zz&!JJ{+	ZZ-
!::&89"JJ':;zz&!jj/JJ{+	$jj)>? &#.#I#I.#Y
 MM"- ))A$wXbNc)d MM$0'7 )"5%3 )!+&6'8"- )*=" "(5A11555s   &
F:1F:c           
          | j                   d
i |j                  }| j                  |      }	  ||fi |}|j                  d      }| j                  |||       d|vr1t        j                  |||j                  j                  d      |       | j                  ||j                  j                  d      |        |j                  d
ddd	t        t        ||             y# t        $ r}t        d|      d}~ww xY w)zEntry point to create imager   z Error registering/creating imageNr  rJ   rU   z AMI creation operation complete.Tr   rV   )r&  r   r  r/   r   r   r   r   r   r   r   rX   ri   )	r   rv   rd   r   r   r  r1   r8   rf   s	            r   r   zCreateImage.do  s	    #D#"C"C"Tfmm"T%%&=>	G?'>?Eyy+H 	VX.&==  VV]]5F5Fv5NPXY"":v}}/@/@AU/VX`a 	
2D	
DPQ`akmuQvDw	
  	G BAFF	Gs   C& &	D /C;;D N)r    r!   r"   r   r   r   r   r   r  r  r&  r   r   rV   r   r   r   r     s    v v   ] ] ] ](  
 $ $6 56 56n 
 
r   r   c                     ddidddddiddiddiddiddiddgdddid		} t        d:i d
ddiddddddg dddddddddiddd| ddddidi di di di d t        dt        t        dd      t        dd      t        dd      t        dd      !      "      d#i d$dddd%ddd&d'i d(i d)i d*d+d+d,gd-d.dd/gdd0ddid1ddid2dd3id4ddd&d5d6dd}t        |d*d,dgggd7      }t        |fi |j                   |j	                  d8      }d}d}d}d}||t
        j                  t        j                  d9|d+t        j                  ii||t
        j                  t        j                  d9|d+t        j                  iii}||j                     t        |j                  j                  d               |j                  d*      }		  |	|||j                  j                  d             y # t        $ r]}
|
j                  r'|j                  |
j                  |
j                          n |j#                  |
j                          Y d }
~
y Y d }
~
y d }
~
ww xY w);Ntypeboolrc   T)r)  requiredr  r-   )r)  aliases)	r,   r&   r+   r  r	  r)   r.   r(   r*   r:   defaultx86_64r  r   )r)  elementsrz   )zlegacy-biosrs   zuefi-preferred)r)  choicesr   F)r-  r)  r>   r  r{   r0   )r)  r/  optionsrL   r8   rC   rw   rP   rU   )r   r   r   r   )r)  r1  rI   r  r   )r)  r-  rR   rF   rS   r9   rt   absent)r-  r0  rJ   resource_tagsrx   ry   rH   hvmr   r   i  )argument_specrequired_ifsupports_check_modeec2)r2  rt   rV   )r0   r   r}   r   clientr   r   r   r   r   r   r*  r/   r   r   fail_json_awsr   ru   )mapping_optionsr5  rv   rd   CHECK_MODE_TRUECHECK_MODE_FALSEHAS_IMAGE_ID_TRUEHAS_IMAGE_ID_FALSEfunc_mappingr  rf   s              r   mainrA    sM   "(&!1 %48f%f% %6(;
O  "*""(e<" !-VW" %*6:	"
 O" !'FW" $V," " " " "  6E: fu=6E:"?	
"* +", $V4-". #t4/"0 1"2 3"4 5"6 $H0EF7"8 /):;9": UO;"< 5/="> '.?"@ /A"B "&u5C"MH #h-
 !F F,fmm,u%JO 	/*G*GT_TbTbcK,E,E F
 	/*<*<XKNN ;
	L ))*40A0A*0M+NOPVP]P]^ePfgD(VZ!2!2:!>? (<<  qyy9QYY'' :(s   #H 	I'
AI""I'__main__r   )NNNNNNNN)$DOCUMENTATIONEXAMPLESRETURNr   0ansible.module_utils.common.dict_transformationsr   7ansible_collections.amazon.aws.plugins.module_utils.ec2r   r   r   r   r   r	   r
   r   r   r   ;ansible_collections.amazon.aws.plugins.module_utils.modulesr   ;ansible_collections.amazon.aws.plugins.module_utils.taggingr   r   ;ansible_collections.amazon.aws.plugins.module_utils.waitersr   	Exceptionr   r6   rX   ri   rq   r}   r   r   r   rA  r    rV   r   r   <module>rL     s   @HkZU
n  U S P P S T \ S S Z R X f ` _I *>2
 	

4F( F(Ro[ o[dd
 d
NR(j zF r   