

# Amazon Machine Images in Amazon EC2
Amazon Machine Images

An Amazon Machine Image (AMI) is an image that provides the software that is required to set up and boot an Amazon EC2 instance. Each AMI also contains a block device mapping that specifies the block devices to attach to the instances that you launch. You must specify an AMI when you launch an instance. The AMI must be compatible with the instance type that you chose for your instance. You can use an AMI provided by AWS, a public AMI, an AMI that someone else shared with you, or an AMI that you purchased from the AWS Marketplace.

An AMI is specific to the following:
+ Region
+ Operating system
+ Processor architecture
+ Root volume type
+ Virtualization type

You can launch multiple instances from a single AMI when you require multiple instances with the same configuration. You can use different AMIs to launch instances when you require instances with different configurations, as shown in the following diagram.

![\[Launch multiple instances from an AMI.\]](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/images/launch-from-ami.png)


You can create an AMI from your Amazon EC2 instances and then use it to launch instances with the same configuration. You can copy an AMI to another AWS Region, and then use it to launch instances in that Region. You can also share an AMI that you created with other accounts so that they can launch instances with the same configuration. You can sell your AMI using the AWS Marketplace.

**Topics**
+ [AMI characteristics](ComponentsAMIs.md)
+ [Find an AMI](finding-an-ami.md)
+ [Paid AMIs in the AWS Marketplace](paid-amis.md)
+ [AMI lifecycle](ami-lifecycle.md)
+ [Boot modes](ami-boot.md)
+ [AMI encryption](AMIEncryption.md)
+ [Shared AMIs](sharing-amis.md)
+ [Monitor AMI events](monitor-ami-events.md)
+ [Understand AMI billing](ami-billing-info.md)
+ [AMI quotas](ami-quotas.md)

# AMI types and characteristics in Amazon EC2
AMI characteristics

When you launch an instance, the AMI that you choose must be compatible with the instance type that you choose. You can select an AMI to use based on the following characteristics:
+ [Region](using-regions-availability-zones.md)
+ Operating system
+ Processor architecture
+ [Launch permissions](#launch-permissions)
+ [Root volume type](#storage-for-the-root-device)
+ [Virtualization types](#virtualization_types)

## Launch permissions


Launch permissions determine who can use an AMI to launch instances. You can think of launch permissions as [sharing an AMI](sharing-amis.md)—when you grant launch permissions, you're sharing the AMI with other users. Only the owner of an AMI can determine its availability by specifying launch permissions. Launch permissions fall into the following categories.


| Launch permission | Description | 
| --- | --- | 
| public | The owner grants launch permissions to all AWS accounts. | 
| explicit | The owner grants launch permissions to specific AWS accounts, organizations, or organizational units (OUs). | 
| implicit | The owner has implicit launch permissions for an AMI. | 

Amazon and the Amazon EC2 community provide a large selection of public AMIs. For more information, see [Understand shared AMI usage in Amazon EC2](sharing-amis.md). Developers can charge for their AMIs. For more information, see [Paid AMIs in the AWS Marketplace for Amazon EC2 instances](paid-amis.md).

## Root volume type


All AMIs are categorized as either *backed by Amazon EBS* or *backed by Amazon S3*.
+ Amazon EBS-backed AMI – The root volume for an instance launched from the AMI is an Amazon Elastic Block Store (Amazon EBS) volume created from an Amazon EBS snapshot. Supported for both Linux and Windows AMIs.
+ Amazon S3-backed AMI – The root volume for an instance launched from the AMI is an instance store volume created from a template stored in Amazon S3. Supported for Linux AMIs only. Windows AMIs do not support instance store for the root volume.

For more information, see [Root volumes for your Amazon EC2 instances](RootDeviceStorage.md).

**Note**  
Amazon S3-backed AMIs are considered end of life and are not recommended for new usage. They are only supported on the following older instance types: C1, C3, D2, I2, M1, M2, M3, R3, and X1.

The following table summarizes the important differences when using the two types of AMIs.


| Characteristic | Amazon EBS-backed AMI | Amazon S3-backed AMI | 
| --- | --- | --- | 
| Root volume | EBS volume | Instance store volume | 
| Boot time for an instance | Usually less than 1 minute | Usually less than 5 minutes | 
| Data persistence  |  By default, the root volume is deleted when the instance terminates.\$1 Data on any other EBS volumes persists after instance termination by default.  |  Data on any instance store volumes persists only during the life of the instance.  | 
| Stopped state |  Can be in a stopped state. Even when the instance is stopped and not running, the root volume is persisted in Amazon EBS.  |  Cannot be in a stopped state; instances are running or terminated.  | 
| Modifications |  The instance type, kernel, RAM disk, and user data can be changed while the instance is stopped.  |  Instance attributes are fixed for the life of an instance.  | 
| Charges |  You're charged for instance usage, EBS volume usage, and storing your AMI as an EBS snapshot.  |  You're charged for instance usage and storing your AMI in Amazon S3.  | 
| AMI creation/bundling | Uses a single command/call | Requires installation and use of AMI tools | 

\$1 By default, EBS root volumes have the `DeleteOnTermination` flag set to `true`. For information about how to change this flag so that the volume persists after termination, see [Keep an Amazon EBS root volume after an Amazon EC2 instance terminates](configure-root-volume-delete-on-termination.md).

\$1\$1 Supported with `io2` EBS Block Express only. For more information, see [Provisioned IOPS SSD Block Express volumes](https://docs.aws.amazon.com/ebs/latest/userguide/provisioned-iops.html#io2-block-express) in the *Amazon EBS User Guide*.

# Identify the root volume type determined by your AMI
Identify the AMI root volume type

The AMI that you use to launch an EC2 instance determines the type of the root volume. The root volume of an EC2 instance is either an EBS volume or an instance store volume.

[Nitro-based instances](instance-types.md#instance-hypervisor-type) support only EBS root volumes. The following previous generation instance types are the only instance types that support instance store root volumes: C1, C3, D2, I2, M1, M2, M3, R3, and X1.

------
#### [ Console ]

**To identify the root volume type determined by an AMI**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **AMIs**, and select the AMI.

1. On the **Details** tab, check the value of **Root device type** as follows:
   + `ebs` – Instances launched from this AMI will get an EBS root volume
   + `instance store` – Instances launched from this AMI will get an instance store root volume.

------
#### [ AWS CLI ]

**To identify the root volume type determined by an AMI**  
Use the [describe-images](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) command.

```
aws ec2 describe-images \
    --image-ids ami-0abcdef1234567890 \
    --query Images[].RootDeviceType
```

The following is example output.

```
ebs
```

------
#### [ PowerShell ]

**To identify the root volume type determined by an AMI**  
Use the [Get-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Image.html) cmdlet.

```
(Get-EC2Image `
    -ImageId ami-0abcdef1234567890).RootDeviceType.Value
```

The following is example output.

```
ebs
```

------

## Virtualization types


Amazon Machine Images use one of two types of virtualization: paravirtual (PV) or hardware virtual machine (HVM). The main differences between PV and HVM AMIs are the way in which they boot and whether they can take advantage of special hardware extensions (CPU, network, and storage) for better performance. Windows AMIs are HVM AMIs.

The following table compares HVM and PV AMIs.


| Characteristic | HVM | PV | 
| --- | --- | --- | 
| Description | HVM AMIs are presented with a fully virtualized set of hardware and boot by executing the master boot record of the root block device of your image. This virtualization type provides the ability to run an operating system directly on top of a virtual machine without any modification, as if it were run on the bare-metal hardware. The Amazon EC2 host system emulates some or all of the underlying hardware that is presented to the guest. | PV AMIs boot with a special boot loader called PV-GRUB, which starts the boot cycle and then chain loads the kernel specified in the menu.lst file on your image. Paravirtual guests can run on host hardware that does not have explicit support for virtualization. For more information about PV-GRUB and its use in Amazon EC2, see [User provided kernels](https://docs.aws.amazon.com/linux/al2/ug/UserProvidedKernels.html). | 
| Supported instance types | All current generation instance types support HVM AMIs. | The following previous generation instance types support PV AMIs: C1, C3, M1, M3, M2, and T1. Current generation instance types do not support PV AMIs. | 
| Support for hardware extensions | HVM guests can take advantage of hardware extensions that provide fast access to the underlying hardware on the host system. They are required to use enhanced networking and GPU processing. To pass through instructions to specialized network and GPU devices, the OS must have access to the native hardware platform, and HVM virtualization provides this access. For more information, see [Enhanced networking on Amazon EC2 instances](enhanced-networking.md). | No, they can't take advantage of special hardware extensions such as enhanced networking or GPU processing. | 
| [How to find](finding-an-ami.md) | Verify that the virtualization type of the AMI is set to hvm, using the console or the [describe-images](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) command. | Verify that the virtualization type of the AMI is set to paravirtual, using the console or the [describe-images](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) command. | 

**PV on HVM**  
Paravirtual guests traditionally performed better with storage and network operations than HVM guests because they could leverage special drivers for I/O that avoided the overhead of emulating network and disk hardware, whereas HVM guests had to translate these instructions to emulated hardware. Now PV drivers are available for HVM guests, so operating systems that cannot be ported to run in a paravirtualized environment can still see performance advantages in storage and network I/O by using them. With these PV on HVM drivers, HVM guests can get the same, or better, performance than paravirtual guests.

# Find an AMI that meets the requirements for your EC2 instance
Find an AMI

An AMI includes the components and applications, such as the operating system and type of root volume, required to launch an instance. To launch an instance, you must find an AMI that meets your needs.

When selecting an AMI, consider the following requirements you might have for the instances that you want to launch:
+ The AWS Region of the AMI as AMI IDs are unique to each Region.
+ The operating system (for example, Linux or Windows).
+ The architecture (for example, 32-bit, 64-bit, or 64-bit ARM).
+ The root volume type (for example, Amazon EBS or instance store).
+ The provider (for example, Amazon Web Services).
+ Additional software (for example, SQL Server).

------
#### [ Console ]

You can select from the list of AMIs when you use the launch instance wizard, or you can search all available AMIs using the **Images** page.

**To find a Quick Start AMI using the launch instance wizard**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. From the navigation bar, select the Region in which to launch your instances. You can select any Region that's available to you, regardless of your location. AMI IDs are unique to each AWS Region.

1. From the console dashboard, choose **Launch instance**.

1. Under **Application and OS Images (Amazon Machine Image)**, choose **Quick Start**, choose the operating system (OS) for your instance, and then, from **Amazon Machine Image (AMI)**, select from one of the commonly used AMIs in the list. If you don't see the AMI that you want to use, choose **Browse more AMIs** to browse the full AMI catalog. For more information, see [Application and OS Images (Amazon Machine Image)](ec2-instance-launch-parameters.md#liw-ami).

**To find an AMI using the AMIs page**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. From the navigation bar, select the Region in which to launch your instances. You can select any Region that's available to you, regardless of your location. AMI IDs are unique to each AWS Region.

1. In the navigation pane, choose **AMIs**.

1. (Optional) Use the filter and search options to scope the list of displayed AMIs to see only the AMIs that match your criteria.

   For example, to list all AMIs provided by AWS, choose **Public images**. Then use the search options to further scope the list of displayed AMIs. Choose the **Search** bar and, from the menu, choose **Owner alias**, then the **=** operator, and then the value **amazon**. To find AMIs that match a specific platform, for example Linux or Windows, choose the **Search** bar again to choose **Platform**, then the **=** operator, and then the operating system from the list provided.

1. (Optional) Choose the **Preferences** icon to select which image attributes to display, such as the root volume type. Alternatively, you can select an AMI from the list and view its properties on the **Details** tab.

1. Before you select an AMI, it's important that you check whether it's backed by instance store or by Amazon EBS and that you are aware of the effects of this difference. For more information, see [Root volume type](ComponentsAMIs.md#storage-for-the-root-device).

1. To launch an instance from this AMI, select it and then choose **Launch instance from image**. For more information about launching an instance using the console, see [Launch an EC2 instance using the launch instance wizard in the console](ec2-launch-instance-wizard.md). If you're not ready to launch the instance now, make note of the AMI ID for later.

------
#### [ AWS CLI ]

Use the [describe-images](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) command to find an AMI that meets your requirements. By default, this command returns all AMIs that are public, that you own, and that are shared with you.

**To find an AMI owned by Amazon**  
Use the [describe-images](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) command with the `--owners` option.

```
aws ec2 describe-images --owners amazon
```

**To find a Windows AMI**  
Add the following filter to display only Windows AMIs.

```
--filters "Name=platform,Values=windows"
```

**To find an EBS-backed AMI**  
Add the following filter to display only AMIs backed by Amazon EBS.

```
--filters "Name=root-device-type,Values=ebs"
```

------
#### [ PowerShell ]

Use the [Get-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Image.html) cmdlet to find an AMI that meets your requirements. By default, this cmdlet returns all AMIs that are public, that you own, or that are shared with you.

**To find an AMI owned by Amazon**  
Use the [Get-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Image.html) command with the `-Owner` parameter.

```
Get-EC2Image -Owner amazon
```

**To find a Windows AMI**  
Add the following filter to display only Windows AMIs.

```
-Filter @{Name="platform"; Values="windows"}
```

For additional examples, see [Find an Amazon Machine Image Using Windows PowerShell](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-ec2-get-amis.html) in the *AWS Tools for PowerShell User Guide*.

------

**Related resources**

For more information about AMIs for a specific operating system, see the following:
+ Amazon Linux 2023 – [AL2023 on Amazon EC2](https://docs.aws.amazon.com/linux/al2023/ug/ec2.html) in the *Amazon Linux 2023 User Guide*
+ Ubuntu – [Amazon EC2 AMI Locator](https://cloud-images.ubuntu.com/locator/ec2/) on the *Canonical Ubuntu website*
+ RHEL – [Red Hat Enterprise Linux Images (AMI) Available on Amazon Web Services (AWS)](https://access.redhat.com/solutions/15356) on the Red Hat website
+ Windows Server – [AWS Windows AMI reference](https://docs.aws.amazon.com/ec2/latest/windows-ami-reference/windows-amis.html)

For information about AMIs that you can subscribe to on the AWS Marketplace see [Paid AMIs in the AWS Marketplace for Amazon EC2 instances](paid-amis.md).

For information about using Systems Manager to help your users find the latest AMI that they should use when launching an instance, see the following:
+ [Reference AMIs using Systems Manager parameters](using-systems-manager-parameter-to-find-AMI.md)
+ [Reference the latest AMIs using Systems Manager public parameters](finding-an-ami-parameter-store.md)

# Reference AMIs using Systems Manager parameters
Systems Manager parameters

When you launch an instance using the EC2 launch instance wizard in the Amazon EC2 console, you can either select an AMI from the list, or you can select an AWS Systems Manager parameter that points to an AMI ID (described in this section). If you use automation code to launch your instances, you can specify the Systems Manager parameter instead of the AMI ID.

A Systems Manager parameter is a customer-defined key-value pair that you can create in Systems Manager Parameter Store. The Parameter Store provides a central store to externalize your application configuration values. For more information, see [AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html) in the *AWS Systems Manager User Guide*.

When you create a parameter that points to an AMI ID, make sure that you specify the data type as `aws:ec2:image`. Specifying this data type ensures that when the parameter is created or modified, the parameter value is validated as an AMI ID. For more information, see [Native parameter support for Amazon Machine Image IDs](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-ec2-aliases.html) in the *AWS Systems Manager User Guide*.

**Topics**
+ [

## Use cases
](#systems-manager-parameter-use-case)
+ [

## Permissions
](#systems-manager-permissions)
+ [

## Limitations
](#AMI-systems-manager-parameter-limitations)
+ [

## Launch an instance using a Systems Manager parameter
](#systems-manager-parameter-launch-instance)

## Use cases


When you use Systems Manager parameters to point to AMI IDs, it is easier for your users to select the correct AMI when launching instances. Systems Manager parameters can also simplify the maintenance of automation code.

**Easier for users**

If you require instances to be launched using a specific AMI, and the AMI is regularly updated, we recommend that you require your users to select a Systems Manager parameter to find the AMI. Requiring your users to select a Systems Manager parameter ensures that the latest AMI is used to launch instances.

For example, every month in your organization you might create a new version of your AMI that has the latest operating system and application patches. You also require your users to launch instances using the latest version of your AMI. To ensure that your users use the latest version, you can create a Systems Manager parameter (for example, `golden-ami`) that points to the correct AMI ID. Each time a new version of the AMI is created, you update the AMI ID value in the parameter so that it always points to the latest AMI. Your users don't have to know about the periodic updates to the AMI because they continue to select the same Systems Manager parameter each time. Using a Systems Manager parameter for your AMI makes it easier for them to select the correct AMI for an instance launch.

**Simplify automation code maintenance**

If you use automation code to launch your instances, you can specify the Systems Manager parameter instead of the AMI ID. If a new version of the AMI is created, you can change the AMI ID value in the parameter so that it points to the latest AMI. The automation code that references the parameter doesn’t have to be modified each time a new version of the AMI is created. This simplifies the maintenance of the automation and helps to drive down deployment costs.

**Note**  
Running instances are not affected when you change the AMI ID pointed to by the Systems Manager parameter.

## Permissions


If you use Systems Manager parameters that point to AMI IDs in the launch instance wizard, you must add the following permissions to your IAM policy:
+ `ssm:DescribeParameters` – Grants permission to view and select Systems Manager parameters.
+ `ssm:GetParameters` – Grants permission to retrieve the values of the Systems Manager parameters. 

You can also restrict access to specific Systems Manager parameters. For more information and example IAM policies, see [Example: Use the EC2 launch instance wizard](iam-policies-ec2-console.md#ex-launch-wizard).

## Limitations


AMIs and Systems Manager parameters are Region specific. To use the same Systems Manager parameter name across Regions, create a Systems Manager parameter in each Region with the same name (for example, `golden-ami`). In each Region, point the Systems Manager parameter to an AMI in that Region.

Parameter names are case-sensitive. Backslashes for the parameter name are only necessary when the parameter is part of a hierarchy, for example, `/amis/production/golden-ami`. You can omit the backslash if the parameter is not part of a hierarchy.

## Launch an instance using a Systems Manager parameter


When you launch an instance, instead of specifying an AMI ID, you can specify a Systems Manager parameter that points to an AMI ID.

To specify the parameter programmatically, use the following syntax, where `resolve:ssm` is the standard prefix and `parameter-name` is the unique parameter name.

```
resolve:ssm:parameter-name
```

Systems Manager parameters have version support. Each iteration of a parameter is assigned a unique version number. You can reference the version of the parameter as follows, where `version` is the unique version number. By default, the latest version of the parameter is used when no version is specified.

```
resolve:ssm:parameter-name:version
```

To launch an instance using a public parameter provided by AWS, see [Reference the latest AMIs using Systems Manager public parameters](finding-an-ami-parameter-store.md).

------
#### [ Console ]

**To find an AMI using a Systems Manager parameter**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. From the navigation bar, select the Region in which to launch your instances. You can select any Region that's available to you, regardless of your location.

1. From the console dashboard, choose **Launch instance**.

1. Under **Application and OS Images (Amazon Machine Image)**, choose **Browse more AMIs**.

1. Choose the arrow button to the right of the search bar, and then choose **Search by Systems Manager parameter**.

1. For **Systems Manager parameter**, select a parameter. The corresponding AMI ID appears below **Currently resolves to**.

1. Choose **Search**. The AMIs that match the AMI ID appear in the list.

1. Select the AMI from the list, and choose **Select**.

For more information about launching an instance using the launch instance wizard, see [Launch an EC2 instance using the launch instance wizard in the console](ec2-launch-instance-wizard.md).

------
#### [ AWS CLI ]

**To launch an instance using a Systems Manager parameter**  
Use the [run-instances](https://docs.aws.amazon.com/cli/latest/reference/ec2/run-instances.html) command with the `--image-id` option. This example uses a Systems Manager parameter named **golden-ami**, which specifies an AMI ID.

```
--image-id resolve:ssm:/golden-ami
```

You can create versions of a Systems Manager parameter. The following example specifies version 2 of the **golden-ami** parameter.

```
--image-id resolve:ssm:/golden-ami:2
```

------
#### [ PowerShell ]

**To launch an instance using a Systems Manager parameter**  
Use the [New-EC2Instance](https://docs.aws.amazon.com/powershell/latest/reference/items/New-EC2Instance.html) cmdlet with the `-ImageId` parameter. This example uses a Systems Manager parameter named **golden-ami**, which specifies an AMI ID.

```
-ImageId "resolve:ssm:/golden-ami"
```

You can create versions of a Systems Manager parameter. The following example specifies version 2 of the **golden-ami** parameter.

```
-ImageId "resolve:ssm:/golden-ami:2"
```

------

# Reference the latest AMIs using Systems Manager public parameters
Systems Manager public parameters

AWS Systems Manager provides public parameters for public AMIs maintained by AWS. You can use the public parameters when launching instances to ensure that you're using the latest AMIs. For example, the public parameter `/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-arm64` is available in all Regions and always points to the latest version of the Amazon Linux 2023 AMI for arm64 architecture in a given Region.

The public parameters are available from the following paths:
+ **Linux** – `/aws/service/ami-amazon-linux-latest`
+ **Windows** – `/aws/service/ami-windows-latest`

For more information, see [Working with public parameters](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-public-parameters.html) in the *AWS Systems Manager User Guide*.

## List the Amazon Linux AMIs


------
#### [ AWS CLI ]

**To list the Linux AMIs in the current AWS Region**  
Use the following [get-parameters-by-path](https://docs.aws.amazon.com/cli/latest/reference/ssm/get-parameters-by-path.html) command. The value for the `--path` parameter is specific to Linux AMIs.

```
aws ssm get-parameters-by-path \
    --path /aws/service/ami-amazon-linux-latest \
    --query "Parameters[].Name"
```

------
#### [ PowerShell ]

**To list the Linux AMIs in the current AWS Region**  
Use the [Get-SSMParametersByPath](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-SSMParametersByPath.html) cmdlet.

```
Get-SSMParametersByPath `
    -Path "/aws/service/ami-amazon-linux-latest" | `
    Sort-Object Name | Format-Table Name
```

------

## List the Windows AMIs


------
#### [ AWS CLI ]

**To list the Windows AMIs in the current AWS Region**  
Use the following [get-parameters-by-path](https://docs.aws.amazon.com/cli/latest/reference/ssm/get-parameters-by-path.html) command. The value for the `--path` parameter is specific to Windows AMIs.

```
aws ssm get-parameters-by-path \
    --path /aws/service/ami-windows-latest \
    --query "Parameters[].Name"
```

------
#### [ PowerShell ]

**To list the Windows AMIs in the current AWS Region**  
Use the [Get-SSMParametersByPath](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-SSMParametersByPath.html) cmdlet.

```
Get-SSMParametersByPath `
    -Path "/aws/service/ami-windows-latest" | `
    Sort-Object Name | Format-Table Name
```

------

## Launch an instance using a public parameter


To specify the public parameter when launching an instance, use the following syntax: `resolve:ssm:public-parameter`, where `resolve:ssm` is the standard prefix and `public-parameter` is the path and name of the public parameter.

------
#### [ AWS CLI ]

**To launch an instance using a public parameter**  
Use the [run-instances](https://docs.aws.amazon.com/cli/latest/reference/ec2/run-instances.html) command with the `--image-id` option. This example specifies a Systems Manager public parameter for the image ID to launch an instance using the latest Amazon Linux 2023 AMI

```
--image-id resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64
```

------
#### [ PowerShell ]

**To launch an instance using a public parameter**  
Use the [New-EC2Instance](https://docs.aws.amazon.com/powershell/latest/reference/items/New-EC2Instance.html) cmdlet with the `-ImageId` parameter. This example specifies a Systems Manager public parameter for the image ID to launch an instance using the latest AMI for Windows Server 2022.

```
-ImageId "resolve:ssm:/aws/service/ami-windows-latest/Windows_Server-2022-English-Full-Base"
```

------

For more examples that use Systems Manager parameters, see [Query for the latest Amazon Linux AMI IDs Using AWS Systems Manager Parameter Store](https://aws.amazon.com/blogs/compute/query-for-the-latest-amazon-linux-ami-ids-using-aws-systems-manager-parameter-store/) and [Query for the Latest Windows AMI Using AWS Systems Manager Parameter Store](https://aws.amazon.com/blogs/mt/query-for-the-latest-windows-ami-using-systems-manager-parameter-store/).

# Paid AMIs in the AWS Marketplace for Amazon EC2 instances
Paid AMIs in the AWS Marketplace

A *paid AMI* is an AMI that is listed for sale in the AWS Marketplace. The AWS Marketplace is an online store where you can buy software that runs on AWS, including AMIs that you can use to launch your EC2 instance. The AWS Marketplace AMIs are organized into categories, such as Developer Tools, to enable you to find products to suit your requirements. For more information about AWS Marketplace, see the [AWS Marketplace](https://aws.amazon.com/marketplace) website.

You can purchase AMIs in the AWS Marketplace from a third party, including AMIs that come with service contracts from organizations such as Red Hat. You can also create an AMI and sell it in the AWS Marketplace to other Amazon EC2 users. Building a safe, secure, usable AMI for public consumption is a fairly straightforward process, if you follow a few simple guidelines. For information about how to create and use shared AMIs, see [Understand shared AMI usage in Amazon EC2](sharing-amis.md).

Launching an instance from a paid AMI is the same as launching an instance from any other AMI. No additional parameters are required. The instance is charged according to the rates set by the owner of the AMI, as well as the standard usage fees for the related web services, for example, the hourly rate for running an m5.small instance type in Amazon EC2. Additional taxes might also apply. The owner of the paid AMI can confirm whether a specific instance was launched using that paid AMI. 

**Important**  
Amazon DevPay is no longer accepting new sellers or products. AWS Marketplace is now the single, unified e-commerce platform for selling software and services through AWS. For information about how to deploy and sell software from AWS Marketplace, see [Selling in AWS Marketplace](https://aws.amazon.com/marketplace/partners/management-tour). AWS Marketplace supports AMIs backed by Amazon EBS.

**Topics**
+ [

## Sell your AMI in the AWS Marketplace
](#selling-your-ami)
+ [

# Find a paid AMI
](using-paid-amis-finding-paid-ami.md)
+ [

# Purchase a paid AMI in the AWS Marketplace
](using-paid-amis-purchasing-paid-ami.md)
+ [

# Retrieve the AWS Marketplace product code from your instance
](get-product-code.md)
+ [

# Use paid support for supported AWS Marketplace offerings
](using-paid-amis-support.md)
+ [

## Bills for paid and supported AMIs
](#using-paid-amis-bills)
+ [

# Manage your AWS Marketplace subscriptions
](marketplace-manage-subscriptions.md)

## Sell your AMI in the AWS Marketplace


You can sell your AMI using AWS Marketplace. AWS Marketplace offers an organized shopping experience. Additionally, AWS Marketplace also supports AWS features such as Amazon EBS-backed AMIs, Reserved Instances, and Spot Instances.

For information about how to sell your AMI on the AWS Marketplace, see [Selling in AWS Marketplace](https://aws.amazon.com/marketplace/partners/management-tour). 

# Find a paid AMI


A paid AMI is an Amazon Machine Image (AMI) that is available for purchase. A paid AMI also has a product code. You can find AMIs that are available for purchase in the AWS Marketplace.

------
#### [ Console ]

**To find a paid AMI**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **AMIs**. 

1. Choose **Public images** for the first filter.

1. Do one of the following:
   + If you know the product code, choose **Product code**, then **=**, and then enter the product code.
   + If you do not know the product code, in the Search bar, specify the following filter: **Owner alias=aws-marketplace**. Specify additional filters as needed.

1. Save the ID of the AMI.

------
#### [ AWS CLI ]

**To find a paid AMI**  
Use the following [describe-images](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) command.

```
aws ec2 describe-images --owners aws-marketplace
```

The output includes a large number of images. You can specify filters to help you determine which AMI you need. After you find an AMI, specify its ID in the following command to get its product code.

```
aws ec2 describe-images \
    --image-ids ami-0abcdef1234567890 \
    --query Images[*].ProductCodes[].ProductCodeId
```

The following is example output.

```
[
    "cdef1234abc567def8EXAMPLE"
]
```

If you know the product code, you can filter the results by product code. This example returns the most recent AMI with the specified product code.

```
aws ec2 describe-images \
    --filters "Name=product-code,Values=cdef1234abc567def8EXAMPLE" \
    --query "sort_by(Images, &CreationDate)[-1].[ImageId]"
```

------
#### [ PowerShell ]

**To find a paid AMI**  
Use the [Get-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Image.html) cmdlet.

```
Get-EC2Image -Owner aws-marketplace
```

The output includes a large number of images. You can specify filters to help you determine which AMI you need. After you find an AMI, specify its ID in the following command to get its product code.

```
(Get-EC2Image -ImageId ami-0abcdef1234567890).ProductCodes
```

The following is example output.

```
ProductCodeId             ProductCodeType
-------------             ---------------
cdef1234abc567def8EXAMPLE marketplace
```

If you know the product code, you can filter the results by product code. This example returns the most recent AMI with the specified product code.

```
(Get-EC2Image -Owner aws-marketplace -Filter @{"Name"="product-code";"Value"="cdef1234abc567def8EXAMPLE"} | sort CreationDate -Descending | Select-Object -First 1).ImageId
```

------

# Purchase a paid AMI in the AWS Marketplace
Purchase a paid AMI

You must sign up for (purchase) a paid AMI before you can launch an Amazon EC2 instance using the AMI.

Typically a seller of a paid AMI presents you with information about the AMI, including its price and a link where you can buy it. When you click the link, you're first asked to log into AWS, and then you can purchase the AMI.

## Purchase a paid AMI using the console


You can purchase a paid AMI by using the Amazon EC2 launch wizard. For more information, see [Launch an Amazon EC2 instance from an AWS Marketplace AMI](launch-marketplace-console.md).

## Subscribe to a product using AWS Marketplace


To use the AWS Marketplace, you must have an AWS account. To launch instances from AWS Marketplace products, you must be signed up to use the Amazon EC2 service, and you must be subscribed to the product from which to launch the instance. You can use one of the following methods to subscribe to products in the AWS Marketplace:
+ **AWS Marketplace website**: You can launch preconfigured software quickly with the 1-Click deployment feature. For more information, see [AMI-based products in AWS Marketplace](https://docs.aws.amazon.com/marketplace/latest/buyerguide/buyer-server-products.html).
+ **Amazon EC2 launch wizard**: You can search for an AMI and launch an instance directly from the wizard. For more information, see [Launch an Amazon EC2 instance from an AWS Marketplace AMI](launch-marketplace-console.md).

# Retrieve the AWS Marketplace product code from your instance
Retrieve the product code

You can retrieve the AWS Marketplace product code for your instance using its instance metadata. If the instance has a product code, Amazon EC2 returns it. For more information about retrieving metadata, see [Access instance metadata for an EC2 instance](instancedata-data-retrieval.md).

------
#### [ IMDSv2 ]

**Linux**  
Run the following command from your Linux instance.

```
TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` \
    && curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/product-codes
```

**Windows**  
Run the following cmdlets from your Windows instance.

```
[string]$token = Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token-ttl-seconds" = "21600"} `
    -Method PUT -Uri http://169.254.169.254/latest/api/token
```

```
Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token" = $token} `
    -Method GET -Uri http://169.254.169.254/latest/meta-data/product-codes
```

------
#### [ IMDSv1 ]

**Linux**  
Run the following command from your Linux instance.

```
curl http://169.254.169.254/latest/meta-data/product-codes
```

**Windows**  
Run the following command from your Windows instance.

```
Invoke-RestMethod -Uri http://169.254.169.254/latest/meta-data/product-codes
```

------

# Use paid support for supported AWS Marketplace offerings
Use paid support

Amazon EC2 also enables developers to offer support for software (or derived AMIs). Developers can create support products that you can sign up to use. During sign-up for the support product, the developer gives you a product code, which you must then associate with your own AMI. This enables the developer to confirm that your instance is eligible for support. It also ensures that when you run instances of the product, you are charged according to the terms for the product specified by the developer. 

**Limitations**
+ After you set the product code attribute, it can't be changed or removed.
+ You can't use a support product with Reserved Instances. You always pay the price that's specified by the seller of the support product.

------
#### [ AWS CLI ]

**To associate a product code with your AMI**  
Use the [modify-image-attribute](https://docs.aws.amazon.com/cli/latest/reference/ec2/modify-image-attribute.html) command.

```
aws ec2 modify-image-attribute \
    --image-id ami-0abcdef1234567890 \
    --product-codes "cdef1234abc567def8EXAMPLE"
```

------
#### [ PowerShell ]

**To associate a product code with your AMI**  
Use the [Edit-EC2ImageAttribute](https://docs.aws.amazon.com/powershell/latest/reference/items/Edit-EC2ImageAttribute.html) cmdlet.

```
Edit-EC2ImageAttribute `
    -ImageId ami-0abcdef1234567890 `
    -ProductCode "cdef1234abc567def8EXAMPLE"
```

------

## Bills for paid and supported AMIs


At the end of each month, you receive an email with the amount your credit card has been charged for using any paid or supported AMIs during the month. This bill is separate from your regular Amazon EC2 bill. For more information, see [Paying for products](https://docs.aws.amazon.com/marketplace/latest/buyerguide/buyer-paying-for-products.html) in the *AWS Marketplace Buyer Guide*.

# Manage your AWS Marketplace subscriptions
Manage your subscriptions

On the AWS Marketplace website, you can check your subscription details, view the vendor's usage instructions, manage your subscriptions, and more.

## Check subscription details


**To check your subscription details**

1.  Log in to the [AWS Marketplace](https://aws.amazon.com/marketplace).

1. Choose **Your Marketplace Account**.

1. Choose **Manage your software subscriptions**. 

1. All your current subscriptions are listed. Choose ** Usage Instructions** to view specific instructions for using the product, for example, a username for connecting to your running instance.

## Cancel subscription


**Note**  
Canceling a subscription does not terminate the instances launched with that AMI. We'll continue to bill you for your running instances until they're terminated. You must terminate all instances launched with the AMI in order to stop billing for the subscription.
After you've canceled your subscription, you are no longer able to launch any instances from that AMI. To use that AMI again, you need to resubscribe to it, either on the AWS Marketplace website, or through the launch wizard in the Amazon EC2 console.

**To cancel an AWS Marketplace subscription**

1. To stop billing for the subscription, ensure that you have terminated any instances running from the subscription.
**Warning**  
**Terminating an instance is permanent and irreversible.**  
After you terminate an instance, you can no longer connect to it, and it can't be recovered. All attached Amazon EBS volumes that are configured to be deleted on termination are also permanently deleted and can't be recovered. All data stored on instance store volumes is permanently lost. For more information, see [How instance termination works](how-ec2-instance-termination-works.md).  
Before you terminate an instance, ensure that you have backed up all data that you need to retain after the termination to persistent storage.

   1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

   1. In the navigation pane, choose **Instances**.

   1. Select the instance, and then choose **Instance state**, **Terminate (delete) instance**.

   1. Choose **Terminate (delete)** when prompted for confirmation.

1. Log in to the [AWS Marketplace](https://aws.amazon.com/marketplace), and choose **Your Marketplace Account**, then **Manage your software subscriptions**.

1. Choose **Cancel subscription**. You are prompted to confirm your cancellation. 

# Amazon EC2 AMI lifecycle
AMI lifecycle

An Amazon Machine Image (AMI) is an image that contains the software configuration required to set up and boot an instance. You must specify an AMI when you launch an instance. You can use AMIs provided by Amazon, or you can create your own AMIs. The AMI must be located in the AWS Region in which you want to launch your instance.

The lifecycle of an AMI includes creating, copying, deprecating, disabling, and deleting (deregistering) the AMI.

**Create AMIs.** While Amazon provides AMIs that you can use to launch your instances, you can create custom AMIs tailored to your needs. To create a custom AMI, launch an instance from an existing AMI, customize the instance (for example, install software and configure operating system settings), and then create an AMI from the instance. Any instance customizations are saved to the new AMI, so that instances launched from your new AMI include these customizations.

**Attestable AMIs.** To create an AMI that supports EC2 instance attestation, see [Attestable AMIs](attestable-ami.md).

**Copy AMIs.** You can use an AMI to launch an instance only in the AWS Region in which the AMI is located. If you need to launch instances with the same configuration in multiple Regions, copy the AMI to the other Regions.

**Deprecate AMIs.** To mark an AMI as superseded or out of date, you can set an immediate or future deprecation date. Deprecated AMIs are hidden from AMI listings, but users and services can continue to use deprecated AMIs if they know the AMI ID.

**Disable AMIs.** To temporarily prevent an AMI from being used, you can disable it. When an AMI is disabled, it can't be used to launch new instances. However, if you re-enable the AMI, it can be used to launch instances again. Note that disabling an AMI doesn't affect existing instances that have already been launched from it.

**Deregister (delete) AMIs.** When you no longer need an AMI, you can deregister it, preventing it from being used to launch new instances. If the AMI matches a retention rule, it moves to the Recycle Bin, where it can be restored before its retention period expires, after which it is permanently deleted. If it doesn't match a retention rule, it is permanently deleted immediately. Note that deregistering an AMI does not affect existing instances that were launched from the AMI.

**Automate the AMI lifecycle.** You can use Amazon Data Lifecycle Manager to automate the creation, retention, copy, deprecation, and deregistration of Amazon EBS-backed AMIs and their backing snapshots. You can also use EC2 Image Builder to automate the creation, management, an deployment of customized AMIs. For more information, see [Automate backups with Amazon Data Lifecycle Manager](https://docs.aws.amazon.com/ebs/latest/userguide/snapshot-lifecycle.html) in the *Amazon EBS User Guide* and the [EC2 Image Builder User Guide](https://docs.aws.amazon.com/imagebuilder/latest/userguide/what-is-image-builder.html).

**Topics**
+ [Create an AMI](creating-an-ami-ebs.md)
+ [

# Create an Amazon S3-backed AMI
](creating-an-ami-instance-store.md)
+ [Create an AMI using Windows Sysprep](ami-create-win-sysprep.md)
+ [Copy an AMI](CopyingAMIs.md)
+ [Store and restore an AMI](ami-store-restore.md)
+ [AMI ancestry](ami-ancestry.md)
+ [AMI usage](ec2-ami-usage.md)
+ [Deprecate an AMI](ami-deprecate.md)
+ [Disable an AMI](disable-an-ami.md)
+ [Deregister an AMI](deregister-ami.md)

# Create an Amazon EBS-backed AMI
Create an AMI

You can create your own Amazon EBS-backed AMI from an Amazon EC2 instance or from a snapshot of the root volume of an Amazon EC2 instance.

To create an Amazon EBS-backed AMI from an instance, start by launching an instance using an existing Amazon EBS-backed AMI. This AMI can be one you obtained from the AWS Marketplace, created using [VM Import/Export](https://docs.aws.amazon.com/vm-import/latest/userguide/what-is-vmimport.html), or any other AMI that you can access. After customizing the instance to meet your specific requirements, create and register a new AMI. You can then use the new AMI to launch new instances with your customizations.

**Note**  
To create an AMI that supports EC2 instance attestation, see [Attestable AMIs](attestable-ami.md).

The procedures described below work for Amazon EC2 instances backed by encrypted Amazon Elastic Block Store (Amazon EBS) volumes (including the root volume) as well as for unencrypted volumes.

The AMI creation process is different for Amazon S3-backed AMIs. For more information, see [Create an Amazon S3-backed AMI](creating-an-ami-instance-store.md).

**Topics**
+ [

## Overview of AMI creation from an instance
](#process-creating-an-ami-ebs)
+ [

## Create an AMI from an instance
](#how-to-create-ebs-ami)
+ [

## Create an AMI from a snapshot
](#creating-launching-ami-from-snapshot)

## Overview of AMI creation from an instance


The following diagram summarizes the process for creating an Amazon EBS-backed AMI from a running EC2 instance: Start with an existing AMI, launch an instance, customize it, create a new AMI from it, and finally launch an instance of your new AMI. The numbers in the diagram match the numbers in the description that follows.

![\[Workflow for creating an AMI from an instance\]](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/images/running-instance.png)


**1 – AMI \$11: Start with an existing AMI**  
Find an existing AMI that is similar to the AMI that you'd like to create. This can be an AMI you have obtained from the AWS Marketplace, an AMI that you have created using [VM Import/Export](https://docs.aws.amazon.com/vm-import/latest/userguide/what-is-vmimport.html), or any other AMI that you can access. You'll customize this AMI for your needs.  
In the diagram, **EBS root volume snapshot \$11** indicates that the AMI is an Amazon EBS-backed AMI and that information about the root volume is stored in this snapshot.

**2 – Launch instance from existing AMI**  
The way to configure an AMI is to launch an instance from the AMI on which you'd like to base your new AMI, and then customize the instance (indicated at **3** in the diagram). Then, you'll create a new AMI that includes the customizations (indicated at **4** in the diagram).

**3 – EC2 instance \$11: Customize the instance**  
Connect to your instance and customize it for your needs. Your new AMI will include these customizations.  
You can perform any of the following actions on your instance to customize it:  
+ Install software and applications
+ Copy data
+ Reduce start time by deleting temporary files and defragmenting your hard drive
+ Attach additional EBS volumes

**4 – Create image**  
When you create an AMI from an instance, Amazon EC2 powers down the instance before creating the AMI to ensure that everything on the instance is stopped and in a consistent state during the creation process. If you're confident that your instance is in a consistent state appropriate for AMI creation, you can tell Amazon EC2 not to power down and reboot the instance. Some file systems, such as XFS, can freeze and unfreeze activity, making it safe to create the image without rebooting the instance.  
During the AMI-creation process, Amazon EC2 creates snapshots of your instance's root volume and any other EBS volumes attached to your instance. You're charged for the snapshots until you [deregister the AMI](deregister-ami.md) and delete the snapshots. If any volumes attached to the instance are encrypted, the new AMI only launches successfully on instances that support Amazon EBS encryption.  
Depending on the size of the volumes, it can take several minutes for the AMI-creation process to complete (sometimes up to 24 hours). You might find it more efficient to create snapshots of your volumes before creating your AMI. This way, only small, incremental snapshots need to be created when the AMI is created, and the process completes more quickly (the total time for snapshot creation remains the same).

**5 – AMI \$12: New AMI**  
After the process completes, you have a new AMI and snapshot (**snapshot \$12**) created from the root volume of the instance. If you added instance store volumes or EBS volumes to the instance, in addition to the root volume, the block device mapping for the new AMI contains information for these volumes.  
Amazon EC2 automatically registers the AMI for you.

**6 – Launch instance from new AMI**  
You can use the new AMI to launch an instance.

**7 – EC2 instance \$12: New instance**  
When you launch an instance using the new AMI, Amazon EC2 creates a new EBS volume for the instance's root volume using the snapshot. If you added instance store volumes or EBS volumes when you customized the instance, the block device mapping for the new AMI contains information for these volumes, and the block device mappings for instances that you launch from the new AMI automatically contain information for these volumes. The instance store volumes specified in the block device mapping for the new instance are new and don't contain any data from the instance store volumes of the instance you used to create the AMI. The data on EBS volumes persists. For more information, see [Block device mappings for volumes on Amazon EC2 instances](block-device-mapping-concepts.md).  
When you create a new instance from an EBS-backed AMI, you should initialize both its root volume and any additional EBS storage before putting it into production. For more information, see [Initialize Amazon EBS volumes](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-initialize.html) in the *Amazon EBS User Guide*.

## Create an AMI from an instance


If you have an existing instance, you can create an AMI from this instance.

------
#### [ Console ]

**To create an AMI**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **Instances**.

1. Select the instance from which to create the AMI, and then choose **Actions**, **Image and templates**, **Create image**.
**Tip**  
If this option is disabled, your instance isn't an Amazon EBS-backed instance.

1. On the **Create image** page, specify the following information:

   1. For **Image name**, enter a unique name for the image, up to 127 characters.

   1. For **Image description**, enter an optional description of the image, up to 255 characters.

   1. For **Reboot instance**, either keep the checkbox selected (the default), or clear it.
      + If **Reboot instance** is selected, when Amazon EC2 creates the new AMI, it reboots the instance so that it can take snapshots of the attached volumes while data is at rest, in order to ensure a consistent state.
      + If **Reboot instance** is cleared, when Amazon EC2 creates the new AMI, it does not shut down and reboot the instance.
**Warning**  
If you clear **Reboot instance**, we can't guarantee the file system integrity of the created image.

   1. **Instance volumes** – You can modify the root volume, and add additional Amazon EBS and instance store volumes, as follows:

      1. The root volume is defined in the first row.
         + To change the size of the root volume, for **Size**, enter the required value.
         + If you select **Delete on termination**, when you terminate the instance created from this AMI, the EBS volume is deleted. If you clear **Delete on termination**, when you terminate the instance, the EBS volume is not deleted. For more information, see [Preserve data when an instance is terminated](preserving-volumes-on-termination.md).

      1. To add an EBS volume, choose **Add volume** (which adds a new row). For **Storage type**, choose **EBS**, and fill in the fields in the row. When you launch an instance from your new AMI, additional volumes are automatically attached to the instance. Empty volumes must be formatted and mounted. Volumes based on a snapshot must be mounted.

      1. To add an instance store volume, see [Add instance store volumes to an Amazon EC2 AMI](adding-instance-storage-ami.md). When you launch an instance from your new AMI, additional volumes are automatically initialized and mounted. These volumes do not contain data from the instance store volumes of the running instance on which you based your AMI.

   1. **Snapshot destination** – If your instance volumes are in a Local Zone that supports EBS local snapshots, choose where to create the AMI’s snapshots:
      + **AWS Region**: Create snapshots in the parent Region of the Local Zone of your volumes.
      + **AWS Local Zone**: Create snapshots in the same Local Zone as your volumes.
**Note**  
This option appears only in Local Zones that support EBS local snapshots, and only if your instance was created in a Local Zone. If the volume is in a Region, this option does not appear, and the snapshot is automatically created in the same Region as the volume. For more information, see [Local snapshots in Local Zones](https://docs.aws.amazon.com/ebs/latest/userguide/snapshots-localzones.html) in the *Amazon EBS User Guide*.
**Important**  
All snapshots of the instance’s volumes must be in the same location. Verify the location of existing snapshots. If any existing snapshots are in a different location than your selected destination, the AMI creation will fail.

   1. **Tags** – You can tag the AMI and the snapshots with the same tags, or you can tag them with different tags.
      + To tag the AMI and the snapshots with the *same* tags, choose **Tag image and snapshots together**. The same tags are applied to the AMI and every snapshot that is created.
      + To tag the AMI and the snapshots with *different* tags, choose **Tag image and snapshots separately**. Different tags are applied to the AMI and the snapshots that are created. However, all the snapshots get the same tags; you can't tag each snapshot with a different tag.

      To add a tag, choose **Add tag**, and enter the key and value for the tag. Repeat for each tag.

   1. When you're ready to create your AMI, choose **Create image**. 

1. To view the status of your AMI while it is being created:

   1. In the navigation pane, choose **AMIs**.

   1. Set the filter to **Owned by me**, and find your AMI in the list.

      Initially, the status is `pending` but should change to `available` after a few minutes.

1. (Optional) To view the snapshot that was created for the new AMI:

   1. Note the ID of your AMI that you located in the previous step.

   1. In the navigation pane, choose **Snapshots**.

   1. Set the filter to **Owned by me**, and then find the snapshot with the new AMI ID in the **Description** column.

      When you launch an instance from this AMI, Amazon EC2 uses this snapshot to create the instance's root volume.

------
#### [ AWS CLI ]

**To create an AMI**  
Use the [create-image](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-image.html) command.

```
aws ec2 create-image \
    --instance-id i-1234567890abcdef0 \
    --name "my-web-server" \
    --description "My web server image" \
    --no-reboot
```

------
#### [ PowerShell ]

**To create an AMI**  
Use the [New-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/New-EC2Image.html) cmdlet.

```
New-EC2Image `
    -InstanceId i-1234567890abcdef0 ` 
    -Name "my-web-server" `
    -Description "My web server image" `
    -NoReboot $true
```

------

## Create an AMI from a snapshot


If you have a snapshot of the root volume of an instance, you can create an AMI from this snapshot.

**Note**  
In most cases, AMIs for Windows, Red Hat, SUSE, and SQL Server require correct licensing information to be present on the AMI. For more information, see [Understand AMI billing information](ami-billing-info.md). When creating an AMI from a snapshot, the `RegisterImage` operation derives the correct billing information from the snapshot's metadata, but this requires the appropriate metadata to be present. To verify if the correct billing information was applied, check the **Platform details** field on the new AMI. If the field is empty or doesn't match the expected operating system code (for example, Windows, Red Hat, SUSE, or SQL), the AMI creation was unsuccessful, and you should discard the AMI and follow the instructions in [Create an AMI from an instance](#how-to-create-ebs-ami).

------
#### [ Console ]

**To create an AMI from a snapshot**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **Snapshots**.

1. Select the snapshot from which to create the AMI, and then choose **Actions**, **Create image from snapshot**.

1. On the **Create image from snapshot** page, specify the following information:

   1. For **Image name**, enter a descriptive name for the image.

   1. For **Description**, enter a brief description for the image.

   1. For **Architecture**, choose the image architecture. Choose **i386** for 32-bit, **x86\$164** for 64-bit, **arm64** for 64-bit ARM, or **x86\$164** for 64-bit macOS.

   1. For **Root device name**, enter the device name to use for the root volume. For more information, see [Device names for volumes on Amazon EC2 instances](device_naming.md).

   1. For **Virtualization type**, choose the virtualization type to be used by instances launched from this AMI. For more information, see [Virtualization types](ComponentsAMIs.md#virtualization_types).

   1. (For paravirtual virtualization only) For **Kernel ID**, select the operating system kernel for the image. If you're using a snapshot of the root volume of an instance, select the same kernel ID as the original instance. If you're unsure, use the default kernel.

   1. (For paravirtual virtualization only) For **RAM disk ID**, select the RAM disk for the image. If you select a specific kernel, you may need to select a specific RAM disk with the drivers to support it.

   1. For **Boot mode**, choose the boot mode for the image, or choose **Use default** so that when an instance is launched with this AMI, it boots with the boot mode supported by the instance type. For more information, see [Set the boot mode of an Amazon EC2 AMI](set-ami-boot-mode.md).

   1. (Optional) Under **Block device mappings**, customize the root volume and add additional data volumes. 

      For each volume, you can specify the size, type, performance characteristics, the behavior of delete on termination, and encryption status. For the root volume, the size can't be smaller than the size of the snapshot. For volume type, General Purpose SSD `gp3` is the default selection.

   1. (Optional) Under **Tags**, you can add one or more tags to the new AMI. To add a tag, choose **Add tag**, and enter the key and value for the tag. Repeat for each tag.

   1. When you're ready to create your AMI, choose **Create image**.

1. (Windows, Red Hat, SUSE, and SQL Server only) To verify if the correct billing information was applied, check the **Platform details** field on the new AMI. If the field is empty or doesn't match the expected operating system code (for example, **Windows** or **Red Hat**), the AMI creation was unsuccessful, and you should discard the AMI and follow the instructions in [Create an AMI from an instance](#how-to-create-ebs-ami).

------
#### [ AWS CLI ]

**To create an AMI from a snapshot using the AWS CLI**  
Use the [register-image](https://docs.aws.amazon.com/cli/latest/reference/ec2/register-image.html) command.

```
aws ec2 register-image \
    --name my-image \
    --root-device-name /dev/xvda \
    --block-device-mappings DeviceName=/dev/xvda,Ebs={SnapshotId=snap-0db2cf683925d191f}
```

------
#### [ PowerShell ]

**To create an AMI from a snapshot using PowerShell**  
Use the [Register-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Register-EC2Image.html) cmdlet.

```
$block = @{SnapshotId=snap-0db2cf683925d191f}
Register-EC2Image `
    -Name my-image `
    -RootDeviceName /dev/xvda `
    -BlockDeviceMapping @{DeviceName="/dev/xvda";Ebs=$block}
```

------

# Create an Amazon S3-backed AMI


The AMI that you specify when you launch your instance determines the type of root volume.

To create an Amazon S3-backed Linux AMI, start from an instance that you've launched from an existing Amazon S3-backed Linux AMI. After you've customized the instance to suit your needs, bundle the volume and register a new AMI, which you can use to launch new instances with these customizations.

You can't create an Amazon S3-backed Windows AMI because Windows AMIs don't support instance store for the root volume.

**Important**  
Only the following instance types support an instance store volume as the root volume and require an Amazon S3-backed AMI: C1, C3, D2, I2, M1, M2, M3, R3, and X1.

The AMI creation process is different for Amazon EBS-backed AMIs. For more information, see [Create an Amazon EBS-backed AMI](creating-an-ami-ebs.md).

**Topics**
+ [

## Overview of AMI creation
](#process-creating-an-ami-instance-store)
+ [

## Prerequisites
](#bundle-ami-prerequisites)
+ [

## Create an AMI from an Amazon Linux instance
](#amazon_linux_instructions)
+ [

# Set up the Amazon EC2 AMI tools
](set-up-ami-tools.md)
+ [

# Amazon EC2 AMI tools reference
](ami-tools-commands.md)
+ [

# Convert your Amazon S3-backed AMI to an EBS-backed AMI
](Using_ConvertingS3toEBS.md)

## Overview of AMI creation


The following diagram summarizes the process of creating an AMI from an instance with an instance store root volume.

![\[Creating an Amazon S3-backed AMI.\]](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/images/ami_create_instance_store.png)


First, launch an instance from an AMI that's similar to the AMI that you'd like to create. You can connect to your instance and customize it. When the instance is set up the way you want it, you can bundle it. It takes several minutes for the bundling process to complete. After the process completes, you have a bundle, which consists of an image manifest (`image.manifest.xml`) and files (`image.part.`*xx*) that contain a template for the root volume. Next you upload the bundle to your Amazon S3 bucket and then register your AMI.

**Note**  
To upload objects to an S3 bucket for your Amazon S3-backed Linux AMI, ACLs must be enabled for the bucket. Otherwise, Amazon EC2 will not be able to set ACLs on the objects to upload. If your destination bucket uses the bucket owner enforced setting for S3 Object Ownership, this won’t work because ACLs are disabled. For more information, see [Controlling ownership of objects and disabling ACLs for your bucket](https://docs.aws.amazon.com/AmazonS3/latest/userguide/about-object-ownership.html).

When you launch an instance using the new AMI, we create the root volume for the instance using the bundle that you uploaded to Amazon S3. The storage space used by the bundle in Amazon S3 incurs charges to your account until you delete it. For more information, see [Deregister an Amazon EC2 AMI](deregister-ami.md).

If you add instance store volumes to your instance in addition to the root volume, the block device mapping for the new AMI contains information for these volumes, and the block device mappings for instances that you launch from the new AMI automatically contain information for these volumes. For more information, see [Block device mappings for volumes on Amazon EC2 instances](block-device-mapping-concepts.md).

## Prerequisites


Before you can create an AMI, you must complete the following tasks:
+ Install the AMI tools. For more information, see [Set up the Amazon EC2 AMI tools](set-up-ami-tools.md).
+ Install the AWS CLI. For more information, see [Getting started with the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html).
+ Ensure that you have an S3 bucket for the bundle, and that your bucket has ACLs enabled. For more information on configuring ACLs, see [Configuring ACLs](https://docs.aws.amazon.com/AmazonS3/latest/userguide/managing-acls.html).
  + To create an S3 bucket using the AWS Management Console, open the Amazon S3 console at [https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/) and choose **Create Bucket**.
  + To create an S3 bucket with the AWS CLI, you can use the [mb](https://docs.aws.amazon.com/cli/latest/reference/s3/mb.html) command. If your installed version of the AMI tools is 1.5.18 or later, you can also use the `ec2-upload-bundle` command to create the S3 bucket. For more information, see [ec2-upload-bundle](ami-tools-commands.md#ami-upload-bundle).
+ Ensure that the files in your bundle aren't encrypted in the S3 bucket. If you require encryption for your AMI, you can use an EBS-backed AMI instead. For more information, see [Use encryption with EBS-backed AMIs](AMIEncryption.md).
+ Ensure that you have your AWS account ID. For more information, see [View AWS account identifiers](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-identifiers.html) in the *AWS Account Management Reference Guide*.
+ Ensure that you have credentials to use the AWS CLI. For more information, see [Authentication and access credentials for the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-authentication.html) in the *AWS Command Line Interface User Guide*.
+ Ensure that you have an X.509 certificate and corresponding private key.
  + If you need to create an X.509 certificate, see [Manage signing certificates](set-up-ami-tools.md#ami-tools-managing-certs). The X.509 certificate and private key are used to encrypt and decrypt your AMI.
  + [China (Beijing)] Use the `$EC2_AMITOOL_HOME/etc/ec2/amitools/cert-ec2-cn-north-1.pem` certificate.
  + [AWS GovCloud (US-West)] Use the `$EC2_AMITOOL_HOME/etc/ec2/amitools/cert-ec2-gov.pem` certificate.
+ Connect to your instance and customize it. For example, you can install software and applications, copy data, delete temporary files, and modify the Linux configuration.

## Create an AMI from an Amazon Linux instance


The following procedures describe how to create an AMI from an instance with an instance store root volume running Amazon Linux 1. They might not work for instances running other Linux distributions.

**To prepare to use the AMI tools (HVM instances only)**

1. The AMI tools require GRUB Legacy to boot properly. Use the following command to install GRUB:

   ```
   [ec2-user ~]$ sudo yum install -y grub
   ```

1. Install the partition management packages with the following command:

   ```
   [ec2-user ~]$ sudo yum install -y gdisk kpartx parted
   ```

**To create an AMI from an Amazon Linux instance with an instance store root volume**

This procedure assumes that you have satisfied the prerequisites in [Prerequisites](#bundle-ami-prerequisites).

In the following commands, replace each *user input placeholder* with your own information.

1. Upload your credentials to your instance. We use these credentials to ensure that only you and Amazon EC2 can access your AMI.

   1. Create a temporary directory on your instance for your credentials as follows:

      ```
      [ec2-user ~]$ mkdir /tmp/cert
      ```

      This enables you to exclude your credentials from the created image.

   1. Copy your X.509 certificate and corresponding private key from your computer to the `/tmp/cert` directory on your instance using a secure copy tool such as [scp](linux-file-transfer-scp.md). The `-i my-private-key.pem` option in the following **scp** command is the private key you use to connect to your instance with SSH, not the X.509 private key. For example:

      ```
      you@your_computer:~ $ scp -i my-private-key.pem /path/to/pk-HKZYKTAIG2ECMXYIBH3HXV4ZBEXAMPLE.pem /path/to/cert-HKZYKTAIG2ECMXYIBH3HXV4ZBEXAMPLE.pem ec2-user@ec2-203-0-113-25.compute-1.amazonaws.com:/tmp/cert/
      pk-HKZYKTAIG2ECMXYIBH3HXV4ZBEXAMPLE.pem  100%  717     0.7KB/s   00:00
      cert-HKZYKTAIG2ECMXYIBH3HXV4ZBEXAMPLE.pem  100%  685     0.7KB/s   00:00
      ```

   Alternatively, because these are plain text files, you can open the certificate and key in a text editor and copy their contents into new files in `/tmp/cert`.

1. <a name="step_with_bundle_path_amazon_linux"></a>Prepare the bundle to upload to Amazon S3 by running the [ec2-bundle-vol](ami-tools-commands.md#ami-bundle-vol) command from inside your instance. Be sure to specify the `-e` option to exclude the directory where your credentials are stored. By default, the bundle process excludes files that might contain sensitive information. These files include `*.sw`, `*.swo`, `*.swp`, `*.pem`, `*.priv`, `*id_rsa*`, `*id_dsa*` `*.gpg`, `*.jks`, `*/.ssh/authorized_keys`, and `*/.bash_history`. To include all of these files, use the `--no-filter` option. To include some of these files, use the `--include` option.
**Important**  
By default, the AMI bundling process creates a compressed, encrypted collection of files in the `/tmp` directory that represents your root volume. If you do not have enough free disk space in `/tmp` to store the bundle, you need to specify a different location for the bundle to be stored with the `-d /path/to/bundle/storage` option. Some instances have ephemeral storage mounted at `/mnt` or `/media/ephemeral0` that you can use, or you can also create, attach, and mount a new Amazon EBS) volume to store the bundle. For more information, see [Create an Amazon EBS volume](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-creating-volume.html) in the *Amazon EBS User Guide*.

   1. You must run the **ec2-bundle-vol** command as root. For most commands, you can use **sudo** to gain elevated permissions, but in this case, you should run **sudo -E su** to keep your environment variables.

      ```
      [ec2-user ~]$ sudo -E su
      ```

      Note that bash prompt now identifies you as the root user, and that the dollar sign has been replaced by a hash tag, signalling that you are in a root shell:

      ```
      [root ec2-user]#
      ```

   1. To create the AMI bundle, run the [ec2-bundle-vol](ami-tools-commands.md#ami-bundle-vol) command as follows:

      ```
      [root ec2-user]# ec2-bundle-vol -k /tmp/cert/pk-HKZYKTAIG2ECMXYIBH3HXV4ZBEXAMPLE.pem -c /tmp/cert/cert-HKZYKTAIG2ECMXYIBH3HXV4ZBEXAMPLE.pem -u 123456789012 -r x86_64 -e /tmp/cert --partition gpt
      ```
**Note**  
For the China (Beijing) and AWS GovCloud (US-West) Regions, use the `--ec2cert` parameter and specify the certificates as per the [prerequisites](#bundle-ami-prerequisites).

      It can take a few minutes to create the image. When this command completes, your `/tmp` (or non-default) directory contains the bundle (`image.manifest.xml`, plus multiple `image.part.`*xx* files).

   1. Exit from the root shell.

      ```
      [root ec2-user]# exit
      ```

1. (Optional) To add more instance store volumes, edit the block device mappings in the `image.manifest.xml` file for your AMI. For more information, see [Block device mappings for volumes on Amazon EC2 instances](block-device-mapping-concepts.md).

   1. Create a backup of your `image.manifest.xml` file.

      ```
      [ec2-user ~]$ sudo cp /tmp/image.manifest.xml /tmp/image.manifest.xml.bak
      ```

   1. Reformat the `image.manifest.xml` file so that it is easier to read and edit.

      ```
      [ec2-user ~]$ sudo xmllint --format /tmp/image.manifest.xml.bak > /tmp/image.manifest.xml
      ```

   1. Edit the block device mappings in `image.manifest.xml` with a text editor. The example below shows a new entry for the `ephemeral1` instance store volume. 
**Note**  
For a list of excluded files, see [ec2-bundle-vol](ami-tools-commands.md#ami-bundle-vol). 

      ```
          <block_device_mapping>
            <mapping>
              <virtual>ami</virtual>
              <device>sda</device>
            </mapping>
            <mapping>
              <virtual>ephemeral0</virtual>
              <device>sdb</device>
            </mapping>
            <mapping>
              <virtual>ephemeral1</virtual>
              <device>sdc</device>
            </mapping>
            <mapping>
              <virtual>root</virtual>
              <device>/dev/sda1</device>
            </mapping>
          </block_device_mapping>
      ```

   1. Save the `image.manifest.xml` file and exit your text editor.

1. To upload your bundle to Amazon S3, run the [ec2-upload-bundle](ami-tools-commands.md#ami-upload-bundle) command as follows.

   ```
   [ec2-user ~]$ ec2-upload-bundle -b amzn-s3-demo-bucket/bundle_folder/bundle_name -m /tmp/image.manifest.xml -a your_access_key_id -s your_secret_access_key
   ```
**Important**  
To register your AMI in a Region other than US East (N. Virginia), you must specify both the target Region with the `--region` option and a bucket path that already exists in the target Region or a unique bucket path that can be created in the target Region.

1. (Optional) After the bundle is uploaded to Amazon S3, you can remove the bundle from the `/tmp` directory on the instance using the following **rm** command:

   ```
   [ec2-user ~]$ sudo rm /tmp/image.manifest.xml /tmp/image.part.* /tmp/image
   ```
**Important**  
If you specified a path with the `-d /path/to/bundle/storage` option in [Step 2](#step_with_bundle_path_amazon_linux), use that path instead of `/tmp`.

1. To register your AMI, run the [register-image](https://docs.aws.amazon.com/cli/latest/reference/ec2/register-image.html) command as follows.

   ```
   [ec2-user ~]$ aws ec2 register-image --image-location amzn-s3-demo-bucket/bundle_folder/bundle_name/image.manifest.xml --name AMI_name --virtualization-type hvm
   ```
**Important**  
If you previously specified a Region for the [ec2-upload-bundle](ami-tools-commands.md#ami-upload-bundle) command, specify that Region again for this command.

# Set up the Amazon EC2 AMI tools
Set up the AMI tools

You can use the AMI tools to create and manage Amazon S3-backed Linux AMIs. To use the tools, you must install them on your Linux instance. The AMI tools are available as both an RPM and as a .zip file for Linux distributions that don't support RPM. 

**To set up the AMI tools using the RPM**

1. Install Ruby using the package manager for your Linux distribution, such as yum. For example:

   ```
   [ec2-user ~]$ sudo yum install -y ruby
   ```

1. Download the RPM file using a tool such as wget or curl. For example:

   ```
   [ec2-user ~]$ wget https://s3.amazonaws.com/ec2-downloads/ec2-ami-tools.noarch.rpm
   ```

1. Verify the RPM file's signature using the following command:

   ```
   [ec2-user ~]$ rpm -K ec2-ami-tools.noarch.rpm
   ```

   The command above should indicate that the file's SHA1 and MD5 hashes are `OK.` If the command indicates that the hashes are `NOT OK`, use the following command to view the file's Header SHA1 and MD5 hashes:

   ```
   [ec2-user ~]$ rpm -Kv ec2-ami-tools.noarch.rpm
   ```

   Then, compare your file's Header SHA1 and MD5 hashes with the following verified AMI tools hashes to confirm the file's authenticity:
   + Header SHA1: a1f662d6f25f69871104e6a62187fa4df508f880
   + MD5: 9faff05258064e2f7909b66142de6782

   If your file's Header SHA1 and MD5 hashes match the verified AMI tools hashes, continue to the next step.

1. Install the RPM using the following command:

   ```
   [ec2-user ~]$ sudo yum install ec2-ami-tools.noarch.rpm
   ```

1. Verify your AMI tools installation using the [ec2-ami-tools-version](ami-tools-commands.md#ami-tools-version) command.

   ```
   [ec2-user ~]$ ec2-ami-tools-version
   ```
**Note**  
If you receive a load error such as "cannot load such file -- ec2/amitools/version (LoadError)", complete the next step to add the location of your AMI tools installation to your `RUBYLIB` path.

1. (Optional) If you received an error in the previous step, add the location of your AMI tools installation to your `RUBYLIB` path.

   1. Run the following command to determine the paths to add.

      ```
      [ec2-user ~]$ rpm -qil ec2-ami-tools | grep ec2/amitools/version
      /usr/lib/ruby/site_ruby/ec2/amitools/version.rb
      /usr/lib64/ruby/site_ruby/ec2/amitools/version.rb
      ```

      In the above example, the missing file from the previous load error is located at `/usr/lib/ruby/site_ruby` and `/usr/lib64/ruby/site_ruby`.

   1. Add the locations from the previous step to your `RUBYLIB` path.

      ```
      [ec2-user ~]$ export RUBYLIB=$RUBYLIB:/usr/lib/ruby/site_ruby:/usr/lib64/ruby/site_ruby
      ```

   1. Verify your AMI tools installation using the [ec2-ami-tools-version](ami-tools-commands.md#ami-tools-version) command.

      ```
      [ec2-user ~]$ ec2-ami-tools-version
      ```

**To set up the AMI tools using the .zip file**

1. Install Ruby and unzip using the package manager for your Linux distribution, such as **apt-get**. For example:

   ```
   [ec2-user ~]$ sudo apt-get update -y && sudo apt-get install -y ruby unzip
   ```

1. Download the .zip file using a tool such as wget or curl. For example:

   ```
   [ec2-user ~]$ wget https://s3.amazonaws.com/ec2-downloads/ec2-ami-tools.zip
   ```

1. Unzip the files into a suitable installation directory, such as `/usr/local/ec2`.

   ```
   [ec2-user ~]$ sudo mkdir -p /usr/local/ec2
   $ sudo unzip ec2-ami-tools.zip -d /usr/local/ec2
   ```

   Notice that the .zip file contains a folder ec2-ami-tools-*x*.*x*.*x*, where *x*.*x*.*x* is the version number of the tools (for example, `ec2-ami-tools-1.5.7`).

1. Set the `EC2_AMITOOL_HOME` environment variable to the installation directory for the tools. For example:

   ```
   [ec2-user ~]$ export EC2_AMITOOL_HOME=/usr/local/ec2/ec2-ami-tools-x.x.x
   ```

1. Add the tools to your `PATH` environment variable. For example:

   ```
   [ec2-user ~]$ export PATH=$EC2_AMITOOL_HOME/bin:$PATH
   ```

1. You can verify your AMI tools installation using the [ec2-ami-tools-version](ami-tools-commands.md#ami-tools-version) command.

   ```
   [ec2-user ~]$ ec2-ami-tools-version
   ```

## Manage signing certificates


Certain commands in the AMI tools require a signing certificate (also known as X.509 certificate). You must create the certificate and then upload it to AWS. For example, you can use a third-party tool such as OpenSSL to create the certificate.

**To create a signing certificate**

1. Install and configure OpenSSL.

1. Create a private key using the `openssl genrsa` command and save the output to a `.pem` file. We recommend that you create a 2048- or 4096-bit RSA key.

   ```
   openssl genrsa 2048 > private-key.pem
   ```

1. Generate a certificate using the `openssl req` command.

   ```
   openssl req -new -x509 -nodes -sha256 -days 365 -key private-key.pem -outform PEM -out certificate.pem
   ```

To upload the certificate to AWS, use the [upload-signing-certificate](https://docs.aws.amazon.com/cli/latest/reference/iam/upload-signing-certificate.html) command.

```
aws iam upload-signing-certificate --user-name user-name --certificate-body file://path/to/certificate.pem
```

To list the certificates for a user, use the [list-signing-certificates](https://docs.aws.amazon.com/cli/latest/reference/iam/list-signing-certificates.html) command:

```
aws iam list-signing-certificates --user-name user-name
```

To disable or re-enable a signing certificate for a user, use the [update-signing-certificate](https://docs.aws.amazon.com/cli/latest/reference/iam/update-signing-certificate.html) command. The following command disables the certificate:

```
aws iam update-signing-certificate --certificate-id OFHPLP4ZULTHYPMSYEX7O4BEXAMPLE --status Inactive --user-name user-name
```

To delete a certificate, use the [delete-signing-certificate](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-signing-certificate.html) command:

```
aws iam delete-signing-certificate --user-name user-name --certificate-id OFHPLP4ZULTHYPMSYEX7O4BEXAMPLE
```

# Amazon EC2 AMI tools reference
AMI tools reference

You can use the AMI tools commands to create and manage Amazon S3-backed Linux AMIs. To set up the tools, see [Set up the Amazon EC2 AMI tools](set-up-ami-tools.md).

For information about your access keys, see [Managing access keys for IAM users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html) in the *IAM User Guide*.

**Topics**
+ [

## ec2-ami-tools-version
](#ami-tools-version)
+ [

## ec2-bundle-image
](#ami-bundle-image)
+ [

## ec2-bundle-vol
](#ami-bundle-vol)
+ [

## ec2-delete-bundle
](#ami-delete-bundle)
+ [

## ec2-download-bundle
](#ami-download-bundle)
+ [

## ec2-migrate-manifest
](#ami-migrate-manifest)
+ [

## ec2-unbundle
](#ami-unbundle)
+ [

## ec2-upload-bundle
](#ami-upload-bundle)
+ [

## Common options for AMI tools
](#common-args-ami)

## ec2-ami-tools-version


### Description


Describes the version of the AMI tools.

### Syntax


**ec2-ami-tools-version**

### Output


The version information.

### Example


This example command displays the version information for the AMI tools that you're using.

```
[ec2-user ~]$ ec2-ami-tools-version
1.5.2 20071010
```

## ec2-bundle-image


### Description


Creates an Amazon S3-backed Linux AMI from an operating system image created in a loopback file.

### Syntax


****ec2-bundle-image** -c *path* -k *path* -u *account* -i *path* [-d *path*] [--ec2cert *path*] [-r *architecture*] [--productcodes *code1*,*code2*,...] [-B *mapping*] [-p *prefix*]** 

### Options


`-c, --cert` *path*  
The user's PEM encoded RSA public key certificate file.  
Required: Yes

`-k, --privatekey` *path*  
The path to a PEM-encoded RSA key file. You'll need to specify this key to unbundle this bundle, so keep it in a safe place. Note that the key doesn't have to be registered to your AWS account.  
Required: Yes

`-u, --user ` *account*  
The user's AWS account ID, without dashes.  
Required: Yes

`-i, --image` *path*  
The path to the image to bundle.  
Required: Yes

`-d, --destination` *path*  
The directory in which to create the bundle.  
Default: `/tmp`  
Required: No

`--ec2cert` *path*  
The path to the Amazon EC2 X.509 public key certificate used to encrypt the image manifest.  
The `us-gov-west-1` and `cn-north-1` Regions use a non-default public key certificate and the path to that certificate must be specified with this option. The path to the certificate varies based on the installation method of the AMI tools. For Amazon Linux, the certificates are located at `/opt/aws/amitools/ec2/etc/ec2/amitools/`. If you installed the AMI tools from the RPM or ZIP file in [Set up the Amazon EC2 AMI tools](set-up-ami-tools.md), the certificates are located at `$EC2_AMITOOL_HOME/etc/ec2/amitools/`.  
Required: Only for the `us-gov-west-1` and `cn-north-1` Regions.

`-r, --arch` *architecture*  
Image architecture. If you don't provide the architecture on the command line, you'll be prompted for it when bundling starts.  
Valid values: `i386` \$1 `x86_64`  
Required: No

`--productcodes` *code1,code2,...*  
Product codes to attach to the image at registration time, separated by commas.  
Required: No

`-B, --block-device-mapping` *mapping*  
Defines how block devices are exposed to an instance of this AMI if its instance type supports the specified device.  
Specify a comma-separated list of key-value pairs, where each key is a virtual name and each value is the corresponding device name. Virtual names include the following:  
+ `ami`—The root file system device, as seen by the instance
+ `root`—The root file system device, as seen by the kernel
+ `swap`—The swap device, as seen by the instance
+ `ephemeralN`—The Nth instance store volume
Required: No

`-p, --prefix` *prefix*  
The filename prefix for bundled AMI files.  
Default: The name of the image file. For example, if the image path is `/var/spool/my-image/version-2/debian.img`, then the default prefix is `debian.img`.  
Required: No

`--kernel` *kernel\$1id*  
Deprecated. Use [register-image](https://docs.aws.amazon.com/cli/latest/reference/ec2/register-image.html) to set the kernel.  
Required: No

`--ramdisk` *ramdisk\$1id*  
Deprecated. Use [register-image](https://docs.aws.amazon.com/cli/latest/reference/ec2/register-image.html) to set the RAM disk if required.  
Required: No

### Output


Status messages describing the stages and status of the bundling process.

### Example


This example creates a bundled AMI from an operating system image that was created in a loopback file.

```
[ec2-user ~]$ ec2-bundle-image -k pk-HKZYKTAIG2ECMXYIBH3HXV4ZBEXAMPLE.pem -c cert-HKZYKTAIG2ECMXYIBH3HXV4ZBEXAMPLE.pem -u 111122223333 -i image.img -d bundled/ -r x86_64
Please specify a value for arch [i386]: 
Bundling image file...
Splitting bundled/image.gz.crypt...
Created image.part.00
Created image.part.01
Created image.part.02
Created image.part.03
Created image.part.04
Created image.part.05
Created image.part.06
Created image.part.07
Created image.part.08
Created image.part.09
Created image.part.10
Created image.part.11
Created image.part.12
Created image.part.13
Created image.part.14
Generating digests for each part...
Digests generated.
Creating bundle manifest...
ec2-bundle-image complete.
```

## ec2-bundle-vol


### Description


Creates an Amazon S3-backed Linux AMI by compressing, encrypting, and signing a copy of the root volume for the instance.

Amazon EC2 attempts to inherit product codes, kernel settings, RAM disk settings, and block device mappings from the instance.

By default, the bundle process excludes files that might contain sensitive information. These files include `*.sw`, `*.swo`, `*.swp`, `*.pem`, `*.priv`, `*id_rsa*`, `*id_dsa*` `*.gpg`, `*.jks`, `*/.ssh/authorized_keys`, and `*/.bash_history`. To include all of these files, use the `--no-filter` option. To include some of these files, use the `--include` option.

For more information, see [Create an Amazon S3-backed AMI](creating-an-ami-instance-store.md).

### Syntax


****ec2-bundle-vol** -c *path* -k *path* -u *account* [-d *path*] [--ec2cert *path*] [-r *architecture*] [--productcodes *code1*,*code2*,...] [-B *mapping*] [--all] [-e *directory1*,*directory2*,...] [-i *file1*,*file2*,...] [--no-filter] [-p *prefix*] [-s *size*] [--[no-]inherit] [-v *volume*] [-P *type*] [-S *script*] [--fstab *path*] [--generate-fstab] [--grub-config *path*]** 

### Options


`-c, --cert` *path*  
The user's PEM encoded RSA public key certificate file.  
Required: Yes

`-k, --privatekey ` *path*   
The path to the user's PEM-encoded RSA key file.  
Required: Yes

`-u, --user` *account*  
The user's AWS account ID, without dashes.  
Required: Yes

`-d, --destination` *destination*  
The directory in which to create the bundle.  
Default: `/tmp`  
Required: No

`--ec2cert` *path*  
The path to the Amazon EC2 X.509 public key certificate used to encrypt the image manifest.  
The `us-gov-west-1` and `cn-north-1` Regions use a non-default public key certificate and the path to that certificate must be specified with this option. The path to the certificate varies based on the installation method of the AMI tools. For Amazon Linux, the certificates are located at `/opt/aws/amitools/ec2/etc/ec2/amitools/`. If you installed the AMI tools from the RPM or ZIP file in [Set up the Amazon EC2 AMI tools](set-up-ami-tools.md), the certificates are located at `$EC2_AMITOOL_HOME/etc/ec2/amitools/`.  
Required: Only for the `us-gov-west-1` and `cn-north-1` Regions.

`-r, --arch ` *architecture*  
The image architecture. If you don't provide this on the command line, you'll be prompted to provide it when the bundling starts.  
Valid values: `i386` \$1 `x86_64`  
Required: No

`--productcodes` *code1,code2,...*  
Product codes to attach to the image at registration time, separated by commas.  
Required: No

`-B, --block-device-mapping` *mapping*  
Defines how block devices are exposed to an instance of this AMI if its instance type supports the specified device.  
Specify a comma-separated list of key-value pairs, where each key is a virtual name and each value is the corresponding device name. Virtual names include the following:  
+ `ami`—The root file system device, as seen by the instance
+ `root`—The root file system device, as seen by the kernel
+ `swap`—The swap device, as seen by the instance
+ `ephemeralN`—The Nth instance store volume
Required: No

`-a, --all`  
Bundle all directories, including those on remotely mounted file systems.  
Required: No

`-e, --exclude ` *directory1,directory2,...*  
A list of absolute directory paths and files to exclude from the bundle operation. This parameter overrides the `--all` option. When exclude is specified, the directories and subdirectories listed with the parameter will not be bundled with the volume.  
Required: No

`-i, --include ` *file1,file2,...*  
A list of files to include in the bundle operation. The specified files would otherwise be excluded from the AMI because they might contain sensitive information.  
Required: No

`--no-filter`  
If specified, we won't exclude files from the AMI because they might contain sensitive information.  
Required: No

`-p, --prefix ` *prefix*  
The file name prefix for bundled AMI files.  
Default: `image`  
Required: No

`-s, --size` *size*  
The size, in MB (1024 \$1 1024 bytes), of the image file to create. The maximum size is 10240 MB.   
Default: 10240  
Required: No

`--[no-]inherit`  
Indicates whether the image should inherit the instance's metadata (the default is to inherit). Bundling fails if you enable `--inherit` but the instance metadata is not accessible.  
Required: No

`-v, --volume ` *volume*  
The absolute path to the mounted volume from which to create the bundle.  
Default: The root directory (/)  
Required: No

`-P, --partition` *type*  
Indicates whether the disk image should use a partition table. If you don't specify a partition table type, the default is the type used on the parent block device of the volume, if applicable, otherwise the default is `gpt`.  
Valid values: `mbr` \$1 `gpt` \$1 `none`  
Required: No

`-S, --script` *script*  
A customization script to be run right before bundling. The script must expect a single argument, the mount point of the volume.  
Required: No

`--fstab` *path*  
The path to the fstab to bundle into the image. If this is not specified, Amazon EC2 bundles /etc/fstab.  
Required: No

`--generate-fstab`  
Bundles the volume using an Amazon EC2-provided fstab.  
Required: No

`--grub-config`  
The path to an alternate grub configuration file to bundle into the image. By default, `ec2-bundle-vol` expects either `/boot/grub/menu.lst` or `/boot/grub/grub.conf` to exist on the cloned image. This option allows you to specify a path to an alternative grub configuration file, which will then be copied over the defaults (if present).  
Required: No

`--kernel` *kernel\$1id*  
Deprecated. Use [register-image](https://docs.aws.amazon.com/cli/latest/reference/ec2/register-image.html) to set the kernel.  
Required: No

`--ramdisk`*ramdisk\$1id*  
Deprecated. Use [register-image](https://docs.aws.amazon.com/cli/latest/reference/ec2/register-image.html) to set the RAM disk if required.  
Required: No

### Output


Status messages describing the stages and status of the bundling.

### Example


This example creates a bundled AMI by compressing, encrypting and signing a snapshot of the local machine's root file system. 

```
[ec2-user ~]$ ec2-bundle-vol -d /mnt -k pk-HKZYKTAIG2ECMXYIBH3HXV4ZBEXAMPLE.pem -c cert-HKZYKTAIG2ECMXYIBH3HXV4ZBEXAMPLE.pem -u 111122223333 -r x86_64
  Copying / into the image file /mnt/image...
  Excluding:
       sys
       dev/shm
       proc
       dev/pts
       proc/sys/fs/binfmt_misc
       dev
       media
       mnt
       proc
       sys
       tmp/image
       mnt/img-mnt
  1+0 records in
  1+0 records out
  mke2fs 1.38 (30-Jun-2005)
  warning: 256 blocks unused.

  Splitting /mnt/image.gz.crypt...
  Created image.part.00
  Created image.part.01
  Created image.part.02
  Created image.part.03
  ...
  Created image.part.22
  Created image.part.23
  Generating digests for each part...
  Digests generated.
  Creating bundle manifest...
  Bundle Volume complete.
```

## ec2-delete-bundle


### Description


Deletes the specified bundle from Amazon S3 storage. After you delete a bundle, you can't launch instances from the corresponding AMI.

### Syntax


****ec2-delete-bundle** -b *bucket* -a *access\$1key\$1id* -s *secret\$1access\$1key* [-t *token*] [--url *url*] [--region *region*] [--sigv *version*] [-m *path*] [-p *prefix*] [--clear] [--retry] [-y]** 

### Options


`-b, --bucket `*bucket*  
The name of the Amazon S3 bucket containing the bundled AMI, followed by an optional '/'-delimited path prefix  
Required: Yes

`-a, --access-key` *access\$1key\$1id*  
The AWS access key ID.  
Required: Yes

`-s, --secret-key` *secret\$1access\$1key*  
The AWS secret access key.  
Required: Yes

`-t, --delegation-token` *token*  
The delegation token to pass along to the AWS request. For more information, see [Temporary security credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) in the *IAM User Guide*.  
Required: Only when you are using temporary security credentials.  
Default: The value of the `AWS_DELEGATION_TOKEN` environment variable (if set).

`--region`*region*  
The Region to use in the request signature.  
Default: `us-east-1`  
Required: Required if using signature version 4

`--sigv`*version*  
The signature version to use when signing the request.  
Valid values: `2` \$1 `4`  
Default: `4`  
Required: No

`-m, --manifest`*path*  
The path to the manifest file.  
Required: You must specify `--prefix` or `--manifest`.

`-p, --prefix` *prefix*  
The bundled AMI filename prefix. Provide the entire prefix. For example, if the prefix is image.img, use `-p image.img` and not `-p image`.  
Required: You must specify `--prefix` or `--manifest`.

`--clear`  
Deletes the Amazon S3 bucket if it's empty after deleting the specified bundle.  
Required: No

`--retry`  
Automatically retries on all Amazon S3 errors, up to five times per operation.  
Required: No

`-y, --yes`  
Automatically assumes the answer to all prompts is yes.  
Required: No

### Output


Amazon EC2 displays status messages indicating the stages and status of the delete process.

### Example


This example deletes a bundle from Amazon S3.

```
[ec2-user ~]$ ec2-delete-bundle -b amzn-s3-demo-bucket -a your_access_key_id -s your_secret_access_key
Deleting files:
amzn-s3-demo-bucket/image.manifest.xml
amzn-s3-demo-bucket/image.part.00
amzn-s3-demo-bucket/image.part.01
amzn-s3-demo-bucket/image.part.02
amzn-s3-demo-bucket/image.part.03
amzn-s3-demo-bucket/image.part.04
amzn-s3-demo-bucket/image.part.05
amzn-s3-demo-bucket/image.part.06
Continue? [y/n]
y
Deleted amzn-s3-demo-bucket/image.manifest.xml
Deleted amzn-s3-demo-bucket/image.part.00
Deleted amzn-s3-demo-bucket/image.part.01
Deleted amzn-s3-demo-bucket/image.part.02
Deleted amzn-s3-demo-bucket/image.part.03
Deleted amzn-s3-demo-bucket/image.part.04
Deleted amzn-s3-demo-bucket/image.part.05
Deleted amzn-s3-demo-bucket/image.part.06
ec2-delete-bundle complete.
```

## ec2-download-bundle


### Description


Downloads the specified Amazon S3-backed Linux AMIs from Amazon S3 storage.

### Syntax


****ec2-download-bundle** -b *bucket* -a *access\$1key\$1id* -s *secret\$1access\$1key* -k *path* [--url *url*] [--region *region*] [--sigv *version*] [-m *file*] [-p *prefix*] [-d *directory*] [--retry]** 

### Options


`-b, --bucket` *bucket*  
The name of the Amazon S3 bucket where the bundle is located, followed by an optional '/'-delimited path prefix.  
Required: Yes

`-a, --access-key` *access\$1key\$1id*  
The AWS access key ID.  
Required: Yes

`-s, --secret-key` *secret\$1access\$1key*  
The AWS secret access key.  
Required: Yes

`-k, --privatekey` *path*  
The private key used to decrypt the manifest.  
Required: Yes

`--url` *url*  
The Amazon S3 service URL.  
Default: `https://s3.amazonaws.com/`  
Required: No

`--region` *region*  
The Region to use in the request signature.  
Default: `us-east-1`  
Required: Required if using signature version 4

`--sigv` *version*  
The signature version to use when signing the request.  
Valid values: `2` \$1 `4`  
Default: `4`  
Required: No

`-m, --manifest` *file*  
The name of the manifest file (without the path). We recommend that you specify either the manifest (`-m`) or a prefix (`-p`).  
Required: No

`-p, --prefix ` *prefix*  
The filename prefix for the bundled AMI files.  
Default: `image`  
Required: No

`-d, --directory ` *directory*  
The directory where the downloaded bundle is saved. The directory must exist.  
Default: The current working directory.  
Required: No

 `--retry`   
Automatically retries on all Amazon S3 errors, up to five times per operation.  
Required: No

### Output


Status messages indicating the various stages of the download process are displayed.

### Example


This example creates the `bundled` directory (using the Linux **mkdir** command) and downloads the bundle from the `amzn-s3-demo-bucket` Amazon S3 bucket.

```
[ec2-user ~]$ mkdir bundled
[ec2-user ~]$ ec2-download-bundle -b amzn-s3-demo-bucket/bundles/bundle_name -m image.manifest.xml -a your_access_key_id -s your_secret_access_key -k pk-HKZYKTAIG2ECMXYIBH3HXV4ZBEXAMPLE.pem -d mybundle
Downloading manifest image.manifest.xml from amzn-s3-demo-bucket to mybundle/image.manifest.xml ...
Downloading part image.part.00 from amzn-s3-demo-bucket/bundles/bundle_name to mybundle/image.part.00 ...
Downloaded image.part.00 from amzn-s3-demo-bucket
Downloading part image.part.01 from amzn-s3-demo-bucket/bundles/bundle_name to mybundle/image.part.01 ...
Downloaded image.part.01 from amzn-s3-demo-bucket
Downloading part image.part.02 from amzn-s3-demo-bucket/bundles/bundle_name to mybundle/image.part.02 ...
Downloaded image.part.02 from amzn-s3-demo-bucket
Downloading part image.part.03 from amzn-s3-demo-bucket/bundles/bundle_name to mybundle/image.part.03 ...
Downloaded image.part.03 from amzn-s3-demo-bucket
Downloading part image.part.04 from amzn-s3-demo-bucket/bundles/bundle_name to mybundle/image.part.04 ...
Downloaded image.part.04 from amzn-s3-demo-bucket
Downloading part image.part.05 from amzn-s3-demo-bucket/bundles/bundle_name to mybundle/image.part.05 ...
Downloaded image.part.05 from amzn-s3-demo-bucket
Downloading part image.part.06 from amzn-s3-demo-bucket/bundles/bundle_name to mybundle/image.part.06 ...
Downloaded image.part.06 from amzn-s3-demo-bucket
```

## ec2-migrate-manifest


### Description


Modifies an Amazon S3-backed Linux AMI (for example, its certificate, kernel, and RAM disk) so that it supports a different Region.

### Syntax


****ec2-migrate-manifest** -c *path* -k *path* -m *path* \$1(-a *access\$1key\$1id* -s *secret\$1access\$1key* --region *region*) \$1 (--no-mapping)\$1 [--ec2cert *ec2\$1cert\$1path*] [--kernel *kernel-id*] [--ramdisk *ramdisk\$1id*]** 

### Options


`-c, --cert` *path*  
The user's PEM encoded RSA public key certificate file.  
Required: Yes

`-k, --privatekey` *path*  
The path to the user's PEM-encoded RSA key file.  
Required: Yes

`--manifest` *path*  
The path to the manifest file.  
Required: Yes

`-a, --access-key` *access\$1key\$1id*  
The AWS access key ID.  
Required: Required if using automatic mapping.

`-s, --secret-key ` *secret\$1access\$1key*  
The AWS secret access key.  
Required: Required if using automatic mapping.

`--region` *region*  
The Region to look up in the mapping file.  
Required: Required if using automatic mapping.

`--no-mapping`  
Disables automatic mapping of kernels and RAM disks.  
 During migration, Amazon EC2 replaces the kernel and RAM disk in the manifest file with a kernel and RAM disk designed for the destination region. Unless the `--no-mapping` parameter is given, `ec2-migrate-bundle` might use the `DescribeRegions` and `DescribeImages` operations to perform automated mappings.   
Required: Required if you're not providing the `-a`, `-s`, and `--region` options used for automatic mapping.

`--ec2cert` *path*  
The path to the Amazon EC2 X.509 public key certificate used to encrypt the image manifest.  
The `us-gov-west-1` and `cn-north-1` Regions use a non-default public key certificate and the path to that certificate must be specified with this option. The path to the certificate varies based on the installation method of the AMI tools. For Amazon Linux, the certificates are located at `/opt/aws/amitools/ec2/etc/ec2/amitools/`. If you installed the AMI tools from the ZIP file in [Set up the Amazon EC2 AMI tools](set-up-ami-tools.md), the certificates are located at `$EC2_AMITOOL_HOME/etc/ec2/amitools/`.  
Required: Only for the `us-gov-west-1` and `cn-north-1` Regions.

`--kernel` *kernel\$1id*  
The ID of the kernel to select.  
We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [User provided kernels](https://docs.aws.amazon.com/linux/al2/ug/UserProvidedKernels.html) in the *Amazon Linux 2 User Guide*.
Required: No

`--ramdisk` *ramdisk\$1id*  
The ID of the RAM disk to select.  
We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [User provided kernels](https://docs.aws.amazon.com/linux/al2/ug/UserProvidedKernels.html) in the *Amazon Linux 2 User Guide*.
Required: No

### Output


Status messages describing the stages and status of the bundling process.

### Example


This example copies the AMI specified in the `my-ami.manifest.xml` manifest from the US to the EU.

```
[ec2-user ~]$ ec2-migrate-manifest --manifest my-ami.manifest.xml --cert cert-HKZYKTAIG2ECMXYIBH3HXV4ZBZQ55CLO.pem --privatekey pk-HKZYKTAIG2ECMXYIBH3HXV4ZBZQ55CLO.pem --region eu-west-1 

Backing up manifest...
Successfully migrated my-ami.manifest.xml It is now suitable for use in eu-west-1.
```

## ec2-unbundle


### Description


Re-creates the bundle from an Amazon S3-backed Linux AMI.

### Syntax


****ec2-unbundle** -k *path* -m *path* [-s *source\$1directory*] [-d *destination\$1directory*]** 

### Options


`-k, --privatekey` *path*  
The path to your PEM-encoded RSA key file.  
Required: Yes

`-m, --manifest` *path*  
The path to the manifest file.  
Required: Yes

`-s, --source` *source\$1directory*  
The directory containing the bundle.  
Default: The current directory.  
Required: No

`-d, --destination` *destination\$1directory*  
The directory in which to unbundle the AMI. The destination directory must exist.   
Default: The current directory.  
Required: No

### Example


This Linux and UNIX example unbundles the AMI specified in the `image.manifest.xml` file.

```
[ec2-user ~]$ mkdir unbundled
$ ec2-unbundle -m mybundle/image.manifest.xml -k pk-HKZYKTAIG2ECMXYIBH3HXV4ZBEXAMPLE.pem -s mybundle -d unbundled
$ ls -l unbundled
total 1025008
-rw-r--r-- 1 root root 1048578048 Aug 25 23:46 image.img
```

### Output


Status messages indicating the various stages of the unbundling process are displayed.

## ec2-upload-bundle


### Description


Uploads the bundle for an Amazon S3-backed Linux AMI to Amazon S3 and sets the appropriate access control lists (ACLs) on the uploaded objects. For more information, see [Create an Amazon S3-backed AMI](creating-an-ami-instance-store.md).

**Note**  
To upload objects to an S3 bucket for your Amazon S3-backed Linux AMI, ACLs must be enabled for the bucket. Otherwise, Amazon EC2 will not be able to set ACLs on the objects to upload. If your destination bucket uses the bucket owner enforced setting for S3 Object Ownership, this won’t work because ACLs are disabled. For more information, see [Controlling ownership of objects and disabling ACLs for your bucket](https://docs.aws.amazon.com/AmazonS3/latest/userguide/about-object-ownership.html).

### Syntax


****ec2-upload-bundle** -b *bucket* -a *access\$1key\$1id* -s *secret\$1access\$1key* [-t *token*] -m *path* [--url *url*] [--region *region*] [--sigv *version*] [--acl *acl*] [-d *directory*] [--part *part*] [--retry] [--skipmanifest]** 

### Options


`-b, --bucket` *bucket*  
The name of the Amazon S3 bucket in which to store the bundle, followed by an optional '/'-delimited path prefix. If the bucket doesn't exist, it's created if the bucket name is available. Additionally, if the bucket doesn't exist and the AMI tools version is 1.5.18 or later, this command sets the ACLs for the bucket.  
Required: Yes

`-a, --access-key` *access\$1key\$1id*  
Your AWS access key ID.  
Required: Yes

`-s, --secret-key` *secret\$1access\$1key*  
Your AWS secret access key.  
Required: Yes

`-t, --delegation-token` *token*  
The delegation token to pass along to the AWS request. For more information, see [Temporary security credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) in the *IAM User Guide*.  
Required: Only when you are using temporary security credentials.  
Default: The value of the `AWS_DELEGATION_TOKEN` environment variable (if set).

`-m, --manifest` *path*  
The path to the manifest file. The manifest file is created during the bundling process and can be found in the directory containing the bundle.  
Required: Yes

`--url` *url*  
Deprecated. Use the `--region` option instead unless your bucket is constrained to the `EU` location (and not `eu-west-1`). The `--location` flag is the only way to target that specific location restraint.  
The Amazon S3 endpoint service URL.  
Default: `https://s3.amazonaws.com/`  
Required: No

`--region` *region*  
The Region to use in the request signature for the destination S3 bucket.  
+ If the bucket doesn't exist and you don't specify a Region, the tool creates the bucket without a location constraint (in `us-east-1`).
+ If the bucket doesn't exist and you specify a Region, the tool creates the bucket in the specified Region.
+ If the bucket exists and you don't specify a Region, the tool uses the bucket's location.
+ If the bucket exists and you specify `us-east-1` as the Region, the tool uses the bucket's actual location without any error message, any existing matching files are over-written.
+ If the bucket exists and you specify a Region (other than `us-east-1`) that doesn't match the bucket's actual location, the tool exits with an error.
If your bucket is constrained to the `EU` location (and not `eu-west-1`), use the `--location` flag instead. The `--location` flag is the only way to target that specific location restraint.  
Default: `us-east-1`  
Required: Required if using signature version 4

`--sigv` *version*  
The signature version to use when signing the request.  
Valid values: `2` \$1 `4`  
Default: `4`  
Required: No

`--acl` *acl*  
The access control list policy of the bundled image.  
Valid values: `public-read` \$1 `aws-exec-read`  
Default: `aws-exec-read`  
Required: No

`-d, --directory` *directory*  
The directory containing the bundled AMI parts.  
Default: The directory containing the manifest file (see the `-m` option).  
Required: No

`--part` *part*  
Starts uploading the specified part and all subsequent parts. For example, `--part 04`.  
Required: No

`--retry`  
Automatically retries on all Amazon S3 errors, up to five times per operation.  
Required: No

`--skipmanifest`  
Does not upload the manifest.  
Required: No

`--location` *location*  
Deprecated. Use the `--region` option instead, unless your bucket is constrained to the `EU` location (and not `eu-west-1`). The `--location` flag is the only way to target that specific location restraint.  
The location constraint of the destination Amazon S3 bucket. If the bucket exists and you specify a location that doesn't match the bucket's actual location, the tool exits with an error. If the bucket exists and you don't specify a location, the tool uses the bucket's location. If the bucket doesn't exist and you specify a location, the tool creates the bucket in the specified location. If the bucket doesn't exist and you don't specify a location, the tool creates the bucket without a location constraint (in `us-east-1`).   
Default: If `--region` is specified, the location is set to that specified Region. If `--region` is not specified, the location defaults to `us-east-1`.  
Required: No

### Output


Amazon EC2 displays status messages that indicate the stages and status of the upload process.

### Example


This example uploads the bundle specified by the `image.manifest.xml` manifest.

```
[ec2-user ~]$ ec2-upload-bundle -b amzn-s3-demo-bucket/bundles/bundle_name -m image.manifest.xml -a your_access_key_id -s your_secret_access_key
Creating bucket...
Uploading bundled image parts to the S3 bucket amzn-s3-demo-bucket ...
Uploaded image.part.00
Uploaded image.part.01
Uploaded image.part.02
Uploaded image.part.03
Uploaded image.part.04
Uploaded image.part.05
Uploaded image.part.06
Uploaded image.part.07
Uploaded image.part.08
Uploaded image.part.09
Uploaded image.part.10
Uploaded image.part.11
Uploaded image.part.12
Uploaded image.part.13
Uploaded image.part.14
Uploading manifest ...
Uploaded manifest.
Bundle upload completed.
```

## Common options for AMI tools
Common options

Most of the AMI tools accept the following optional parameters.

`--help, -h`  
Displays the help message.

`--version`  
Displays the version and copyright notice.

`--manual`  
Displays the manual entry.

`--batch`  
Runs in batch mode, suppressing interactive prompts.

`--debug`  
Displays information that can be useful when troubleshooting problems.

# Convert your Amazon S3-backed AMI to an EBS-backed AMI
Convert your S3-backed AMI

You can convert an Amazon S3-backed Linux AMI that you own to an Amazon EBS-backed Linux AMI. 

**Important**  
You can't convert an AMI that you don't own.

**To convert an Amazon S3-backed AMI to an Amazon EBS-backed AMI**

1. Launch an Amazon Linux instance from an Amazon EBS-backed AMI. For more information, see [Launch an EC2 instance using the launch instance wizard in the console](ec2-launch-instance-wizard.md). Amazon Linux instances have the AWS CLI and AMI tools pre-installed.

1. Upload the X.509 private key that you used to bundle your Amazon S3-backed AMI to your instance. We use this key to ensure that only you and Amazon EC2 can access your AMI.

   1. Create a temporary directory on your instance for your X.509 private key as follows:

      ```
      [ec2-user ~]$ mkdir /tmp/cert
      ```

   1. Copy your X.509 private key from your computer to the `/tmp/cert` directory on your instance, using a secure copy tool such as [scp](linux-file-transfer-scp.md). The *my-private-key* parameter in the following command is the private key you use to connect to your instance with SSH. For example:

      ```
      you@your_computer:~ $ scp -i my-private-key.pem /path/to/pk-HKZYKTAIG2ECMXYIBH3HXV4ZBEXAMPLE.pem ec2-user@ec2-203-0-113-25.compute-1.amazonaws.com:/tmp/cert/
      pk-HKZYKTAIG2ECMXYIBH3HXV4ZBEXAMPLE.pem  100%  717     0.7KB/s   00:00
      ```

1. Configure your environment variables to use the AWS CLI. For more information, see [Environment variables](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html).

   1. (Recommended) Set environment variables for your AWS access key, secret key, and session token.

      ```
      [ec2-user ~]$ export AWS_ACCESS_KEY_ID=your_access_key_id
      [ec2-user ~]$ export AWS_SECRET_ACCESS_KEY=your_secret_access_key
      [ec2-user ~]$ export AWS_SESSION_TOKEN=your_session_token
      ```

   1. Set environment variables for your AWS access key, and secret key.

      ```
      [ec2-user ~]$ export AWS_ACCESS_KEY_ID=your_access_key_id
      [ec2-user ~]$ export AWS_SECRET_ACCESS_KEY=your_secret_access_key
      ```

1. Prepare an Amazon Elastic Block Store (Amazon EBS) volume for your new AMI.

   1. Create an empty EBS volume in the same Availability Zone as your instance using the [create-volume](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-volume.html) command. Note the volume ID in the command output.
**Important**  
 This EBS volume must be the same size or larger than the original instance store root volume.

      ```
      aws ec2 create-volume \
          --size 10 \
          --region us-west-2 \
          --availability-zone us-west-2b
      ```

   1. Attach the volume to your Amazon EBS-backed instance using the [attach-volume](https://docs.aws.amazon.com/cli/latest/reference/ec2/attach-volume.html) command.

      ```
      aws ec2 attach-volume \
          --volume-id vol-01234567890abcdef \
          --instance-id i-1234567890abcdef0 \
          --region us-west-2
      ```

1. Create a folder for your bundle.

   ```
   [ec2-user ~]$ mkdir /tmp/bundle
   ```

1. Download the bundle for your instance store-based AMI to `/tmp/bundle` using the [ec2-download-bundle](ami-tools-commands.md#ami-download-bundle) command.

   ```
   [ec2-user ~]$ ec2-download-bundle -b amzn-s3-demo-bucket/bundle_folder/bundle_name -m image.manifest.xml -a $AWS_ACCESS_KEY_ID -s $AWS_SECRET_ACCESS_KEY --privatekey /path/to/pk-HKZYKTAIG2ECMXYIBH3HXV4ZBEXAMPLE.pem -d /tmp/bundle
   ```

1. Reconstitute the image file from the bundle using the [ec2-unbundle](ami-tools-commands.md#ami-unbundle) command.

   1. Change directories to the bundle folder.

      ```
      [ec2-user ~]$ cd /tmp/bundle/
      ```

   1. Run the [ec2-unbundle](ami-tools-commands.md#ami-unbundle) command.

      ```
      [ec2-user bundle]$ ec2-unbundle -m image.manifest.xml --privatekey /path/to/pk-HKZYKTAIG2ECMXYIBH3HXV4ZBEXAMPLE.pem
      ```

1. Copy the files from the unbundled image to the new EBS volume.

   ```
   [ec2-user bundle]$ sudo dd if=/tmp/bundle/image of=/dev/sdb bs=1M
   ```

1. Probe the volume for any new partitions that were unbundled.

   ```
   [ec2-user bundle]$ sudo partprobe /dev/sdb1
   ```

1. List the block devices to find the device name to mount.

   ```
   [ec2-user bundle]$ lsblk
   NAME         MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
   /dev/sda    202:0    0   8G  0 disk
   └─/dev/sda1 202:1    0   8G  0 part /
   /dev/sdb    202:80   0  10G  0 disk
   └─/dev/sdb1 202:81   0  10G  0 part
   ```

   In this example, the partition to mount is `/dev/sdb1`, but your device name will likely be different. If your volume is not partitioned, then the device to mount will be similar to `/dev/sdb` (without a device partition trailing digit).

1. Create a mount point for the new EBS volume and mount the volume.

   ```
   [ec2-user bundle]$ sudo mkdir /mnt/ebs
   [ec2-user bundle]$ sudo mount /dev/sdb1 /mnt/ebs
   ```

1. Open the `/etc/fstab` file on the EBS volume with your favorite text editor (such as **vim** or **nano**) and remove any entries for instance store (ephemeral) volumes. Because the EBS volume is mounted on `/mnt/ebs`, the `fstab` file is located at `/mnt/ebs/etc/fstab`.

   ```
   [ec2-user bundle]$ sudo nano /mnt/ebs/etc/fstab
   #
   LABEL=/     /           ext4    defaults,noatime  1   1
   tmpfs       /dev/shm    tmpfs   defaults        0   0
   devpts      /dev/pts    devpts  gid=5,mode=620  0   0
   sysfs       /sys        sysfs   defaults        0   0
   proc        /proc       proc    defaults        0   0
   /dev/sdb        /media/ephemeral0       auto    defaults,comment=cloudconfig    0       2
   ```

   In this example, the last line should be removed.

1. Unmount the volume and detach it from the instance.

   ```
   [ec2-user bundle]$ sudo umount /mnt/ebs
   [ec2-user bundle]$ aws ec2 detach-volume --volume-id vol-01234567890abcdef --region us-west-2
   ```

1. Create an AMI from the new EBS volume as follows.

   1. Create a snapshot of the new EBS volume.

      ```
      [ec2-user bundle]$ aws ec2 create-snapshot --region us-west-2 --description "your_snapshot_description" --volume-id vol-01234567890abcdef
      ```

   1. Check to see that your snapshot is complete.

      ```
      [ec2-user bundle]$ aws ec2 describe-snapshots --region us-west-2 --snapshot-id snap-0abcdef1234567890
      ```

   1. Identify the processor architecture, virtualization type, and the kernel image (`aki`) used on the original AMI with the **describe-images** command. You need the AMI ID of the original Amazon S3-backed AMI for this step.

      ```
      [ec2-user bundle]$ aws ec2 describe-images --region us-west-2 --image-id ami-0abcdef1234567890 --output text
      IMAGES	x86_64	amazon/amzn-ami-pv-2013.09.2.x86_64-s3	ami-8ef297be	amazon	available	public	machine	aki-fc8f11cc	instance-store	paravirtual	xen
      ```

      In this example, the architecture is `x86_64` and the kernel image ID is `aki-fc8f11cc`. Use these values in the following step. If the output of the above command also lists an `ari` ID, take note of that as well.

   1. Register your new AMI with the snapshot ID of your new EBS volume and the values from the previous step. If the previous command output listed an `ari` ID, include that in the following command with `--ramdisk-id ari_id`.

      ```
      [ec2-user bundle]$ aws ec2 register-image --region us-west-2 --name your_new_ami_name --block-device-mappings DeviceName=device-name,Ebs={SnapshotId=snap-0abcdef1234567890} --virtualization-type paravirtual --architecture x86_64 --kernel-id aki-fc8f11cc --root-device-name device-name
      ```

1. (Optional) After you have tested that you can launch an instance from your new AMI, you can delete the EBS volume that you created for this procedure.

   ```
   aws ec2 delete-volume --volume-id vol-01234567890abcdef
   ```

# Create an Amazon EC2 AMI using Windows Sysprep
Create an AMI using Windows Sysprep

The Microsoft System Preparation (Windows Sysprep) tool creates a generalized version of the operating system, with instance-specific system configuration removed before it captures a new image.

We recommend that you use [EC2 Image Builder](https://docs.aws.amazon.com/imagebuilder/latest/userguide/what-is-image-builder.html) to automate the creation, management, and deployment of customized, secure, and up-to-date "golden" server images that are pre-installed and preconfigured with software and settings.

You can also use Windows Sysprep to create a standardized AMI using the Windows launch agents: EC2Launch v2, EC2Launch, and EC2Config.

**Important**  
Do not use Windows Sysprep to create an instance backup. Windows Sysprep removes system-specific information; removing this information might have unintended consequences for an instance backup.

To troubleshoot Windows Sysprep, see [Troubleshoot Sysprep issues with Amazon EC2 Windows instances](sysprep-troubleshoot.md).

**Topics**
+ [

## Windows Sysprep phases
](#sysprep-phases)
+ [

## Before you begin
](#sysprep-begin)
+ [Use Windows Sysprep with EC2Launch v2](sysprep-using-ec2launchv2.md)
+ [Use Windows Sysprep with EC2Launch](ec2launch-sysprep.md)
+ [Use Windows Sysprep with EC2Config](sysprep-using.md)

## Windows Sysprep phases


Windows Sysprep runs through the following phases:
+ **Generalize**: The Sysprep tool removes image-specific information and configurations. For example, Windows Sysprep removes the security identifier (SID), the computer name, the event logs, and specific drivers, to name a few. After this phase is completed, the operating system (OS) is ready to create an AMI.
**Note**  
When you run Windows Sysprep with the Windows launch agents, the system prevents drivers from being removed because `PersistAllDeviceInstalls` is set to true by default.
+ **Specialize**: Plug and Play scans the computer and installs drivers for any detected devices. The Sysprep tool generates OS requirements, like the computer name and SID. Optionally, you can run commands in this phase.
+ **Out-of-Box Experience (OOBE)**: The system runs an abbreviated version of Windows Setup and asks you to enter information such as system language, time zone, and registered organization. When you run Windows Sysprep with Windows launch agents, the answer file automates this phase.

## Before you begin

+ Before performing Windows Sysprep, we recommend that you remove all local user accounts and all account profiles other than a single administrator account under which Windows Sysprep will be run. If you perform Windows Sysprep with additional accounts and profiles, unexpected behavior could result, including loss of profile data or failure to complete Windows Sysprep.
+ Learn more about [Sysprep Overview](https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/sysprep--system-preparation--overview).
+ Learn which [Sysprep Support for Server Roles](https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/sysprep-support-for-server-roles).

# Create an AMI using Windows Sysprep with EC2Launch v2
Use Windows Sysprep with EC2Launch v2

When you create an image from an instance with the EC2Launch v2 agent installed, EC2Launch v2 performs specific tasks as the image is prepared. This includes working with Windows Sysprep. For more information, see [Windows Sysprep phases](ami-create-win-sysprep.md#sysprep-phases).

**Topics**
+ [

## Windows Sysprep actions
](#sysprep-actions-ec2launchv2)
+ [

## Post Sysprep
](#sysprep-post-ec2launchv2)
+ [

## Run Windows Sysprep with EC2Launch v2
](#sysprep-gui-procedure-ec2launchv2)

## Windows Sysprep actions


Windows Sysprep and EC2Launch v2 perform the following actions when preparing an image.

1. When you choose **Shutdown with Sysprep** in the **EC2Launch settings** dialog box, the system runs the `ec2launch sysprep` command.

1. EC2Launch v2 edits the content of the `unattend.xml` file by reading the registry value at `HKEY_USERS\.DEFAULT\Control Panel\International\LocaleName`. This file is located in the following directory: `C:\ProgramData\Amazon\EC2Launch\sysprep`.

1. The system run the `BeforeSysprep.cmd`. This command creates a registry key as follows:

   **reg add "HKEY\$1LOCAL\$1MACHINE\$1SYSTEM\$1CurrentControlSet\$1Control\$1Terminal Server" /v fDenyTSConnections /t REG\$1DWORD /d 1 /f**

   The registry key disables RDP connections until they are re-enabled. Disabling RDP connections is a necessary security measure because, during the first boot session after Windows Sysprep has run, there is a short period of time where RDP allows connections and the Administrator password is blank.

1. The EC2Launch v2 service calls Windows Sysprep by running the following command:

   **sysprep.exe /oobe /generalize /shutdown /unattend: "C:\$1ProgramData\$1Amazon\$1EC2Launch\$1sysprep\$1unattend.xml"**

### Generalize phase

+ EC2Launch v2 removes image-specific information and configurations, such as the computer name and the SID. If the instance is a member of a domain, it is removed from the domain. The `unattend.xml` answer file includes the following settings that affect this phase: 
  + **PersistAllDeviceInstalls**: This setting prevents Windows Setup from removing and reconfiguring devices, which speeds up the image preparation process because Amazon AMIs require certain drivers to run and re-detection of those drivers would take time.
  + **DoNotCleanUpNonPresentDevices**: This setting retains Plug and Play information for devices that are not currently present.
+ Windows Sysprep shuts down the OS as it prepares to create the AMI. The system either launches a new instance or starts the original instance.

### Specialize phase


The system generates OS-specific requirements, such as a computer name and an SID. The system also performs the following actions based on configurations that you specify in the `unattend.xml` answer file.
+ **CopyProfile**: Windows Sysprep can be configured to delete all user profiles, including the built-in Administrator profile. This setting retains the built-in Administrator account so that any customizations you make to that account are carried over to the new image. The default value is `True`.

  **CopyProfile** replaces the default profile with the existing local administrator profile. All accounts that you log in to after running Windows Sysprep receive a copy of that profile and its contents at first login. 

  If you don’t have specific user-profile customizations that you want to carry over to the new image, then change this setting to `False`. Windows Sysprep will remove all user profiles (this saves time and disk space).
+ **TimeZone**: The time zone is set to Coordinate Universal Time (UTC) by default.
+ **Synchronous command with order 1**: The system runs the following command, which enables the administrator account and specifies the password requirement:

  ```
  net user Administrator /ACTIVE:YES /LOGONPASSWORDCHG:NO /EXPIRES:NEVER /PASSWORDREQ:YES
  ```
+ **Synchronous command with order 2**: The system scrambles the administrator password. This security measure is designed to prevent the instance from being accessible after Windows Sysprep completes if you did not configure the `setAdminAccount` task.

  The system runs the following command from your local launch agent directory (`C:\Program Files\Amazon\EC2Launch\`).

  ```
  EC2Launch.exe internal randomize-password --username Administrator
  ```
+ To enable remote desktop connections, the system sets the Terminal Server `fDenyTSConnections` registry key to false.

### OOBE phase


1. The system specifies the following configurations using the EC2Launch v2 answer file:
   + `<InputLocale>en-US</InputLocale>`
   + `<SystemLocale>en-US</SystemLocale>`
   + `<UILanguage>en-US</UILanguage>`
   + `<UserLocale>en-US</UserLocale>`
   + `<HideEULAPage>true</HideEULAPage>`
   + `<HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE>`
   + `<ProtectYourPC>3</ProtectYourPC>`
   + `<BluetoothTaskbarIconEnabled>false</BluetoothTaskbarIconEnabled>`
   + `<TimeZone>UTC</TimeZone>`
   + `<RegisteredOrganization>Amazon.com</RegisteredOrganization>`
   + `<RegisteredOwner>EC2</RegisteredOwner>`
**Note**  
During the generalize and specialize phases, EC2Launch v2 monitors the status of the OS. If EC2Launch v2 detects that the OS is in a Sysprep phase, then it publishes the following message to the system log:  
Windows is being configured. SysprepState=IMAGE\$1STATE\$1UNDEPLOYABLE

1. The system runs EC2Launch v2.

## Post Sysprep


After Windows Sysprep completes, EC2Launch v2 sends the following message to the console output:

```
Windows sysprep configuration complete.
```

EC2Launch v2 then performs the following actions:

1. Reads the content of the `agent-config.yml` file and runs configured tasks. 

1. Executes all tasks in the `preReady` stage.

1. After it is finished, sends a `Windows is ready` message to the instance system logs.

1. Executes all tasks in the `PostReady` stage.

For more information about EC2Launch v2 , see [Use the EC2Launch v2 agent to perform tasks during EC2 Windows instance launch](ec2launch-v2.md).

## Run Windows Sysprep with EC2Launch v2


Use the following procedure to create a standardized AMI using Windows Sysprep with EC2Launch v2.

1. In the Amazon EC2 console, locate an AMI that you want to duplicate.

1. Launch and connect to your Windows instance.

1. Customize settings

   1. From the Windows **Start** menu, search for and choose **Amazon EC2Launch settings**. For more information about the options and settings in the Amazon **EC2Launch settings** dialog box, see [Configure EC2Launch v2 settings for Windows instances](ec2launch-v2-settings.md).

   1. If you've made changes, choose **Save** before you shut down.

1. Choose **Shutdown with Sysprep** or **Shutdown without Sysprep**.

When you are asked to confirm that you want to run Windows Sysprep and shut down the instance, click **Yes**. EC2Launch v2 runs Windows Sysprep. Next, you are logged off the instance, and the instance shuts down. If you check the **Instances** page in the Amazon EC2 console, the instance state changes from `Running` to `Stopping` to `Stopped`. At this point, it's safe to create an AMI from this instance.

You can manually invoke the Windows Sysprep tool from the command line using the following command:

```
"%programfiles%\amazon\ec2launch\ec2launch.exe" sysprep --shutdown=true
```

# Create an AMI using Windows Sysprep with EC2Launch
Use Windows Sysprep with EC2Launch

When you create an image from an instance with the EC2Launch agent installed, EC2Launch performs specific tasks as the image is prepared. This includes working with Windows Sysprep. For more information, see [Windows Sysprep phases](ami-create-win-sysprep.md#sysprep-phases).

EC2Launch offers a default answer file and batch files for Windows Sysprep that automate and secure the image-preparation process on your AMI. Modifying these files is optional. These files are located in the following directory by default: `C:\ProgramData\Amazon\EC2-Windows\Launch\Sysprep`.

**Important**  
Do not use Windows Sysprep to create an instance backup. Windows Sysprep removes system-specific information. If you remove this information there might be unintended consequences for an instance backup.

**Topics**
+ [

## EC2Launch answer and batch files for Windows Sysprep
](#ec2launch-sysprep-answer-batch)
+ [

## Run Windows Sysprep with EC2Launch
](#ec2launch-sysprep-running)
+ [

## Update metadata/KMS routes for Server 2016 and later when launching a custom AMI
](#update-metadata-KMS)

## EC2Launch answer and batch files for Windows Sysprep


The EC2Launch answer file and batch files for Windows Sysprep include the following:

`Unattend.xml`  
This is the default answer file. If you run `SysprepInstance.ps1` or choose **ShutdownWithSysprep** in the user interface, the system reads the setting from this file.

`BeforeSysprep.cmd`  
Customize this batch file to run commands before EC2Launch runs Windows Sysprep.

`SysprepSpecialize.cmd`  
Customize this batch file to run commands during the Windows Sysprep specialize phase.

## Run Windows Sysprep with EC2Launch


On the full installation of Windows Server 2016 and later (with a desktop experience), you can run Windows Sysprep with EC2Launch manually or by using the **EC2 Launch Settings** application.

**To run Windows Sysprep using the EC2Launch Settings application**

1. In the Amazon EC2 console, locate or create a Windows Server 2016 or later AMI.

1. Launch a Windows instance from the AMI.

1. Connect to your Windows instance and customize it.

1. Search for and run the **EC2LaunchSettings** application. It is located in the following directory by default: `C:\ProgramData\Amazon\EC2-Windows\Launch\Settings`.  
![\[EC2 Launch Settings application\]](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/images/ec2launch-sysprep.png)

1. Select or clear options as needed. These settings are stored in the `LaunchConfig.json` file.

1. For **Administrator Password**, do one of the following:
   + Choose **Random**. EC2Launch generates a password and encrypts it using the user's key. The system disables this setting after the instance is launched so that this password persists if the instance is rebooted or stopped and started.
   + Choose **Specify** and type a password that meets the system requirements. The password is stored in `LaunchConfig.json` as clear text and is deleted after Windows Sysprep sets the administrator password. If you shut down now, the password is set immediately. EC2Launch encrypts the password using the user's key.
   + Choose **DoNothing** and specify a password in the `unattend.xml` file. If you don't specify a password in `unattend.xml`, the administrator account is disabled.

1. Choose **Shutdown with Sysprep**.

**To manually run Windows Sysprep using EC2Launch**

1. In the Amazon EC2 console locate or create a Windows Server 2016 or later Datacenter edition AMI that you want to duplicate.

1. Launch and connect to your Windows instance.

1. Customize the instance.

1. Specify settings in the `LaunchConfig.json` file. This file is located in the `C:\ProgramData\Amazon\EC2-Windows\Launch\Config` directory by default.

   For `adminPasswordType`, specify one of the following values:  
`Random`  
EC2Launch generates a password and encrypts it using the user's key. The system disables this setting after the instance is launched so that this password persists if the instance is rebooted or stopped and started.  
`Specify`  
EC2Launch uses the password you specify in `adminPassword`. If the password does not meet the system requirements, EC2Lauch generates a random password instead. The password is stored in `LaunchConfig.json` as clear text and is deleted after Windows Sysprep sets the administrator password. EC2Launch encrypts the password using the user's key.  
`DoNothing`  
EC2Launch uses the password you specify in the `unattend.xml` file. If you don't specify a password in `unattend.xml`, the administrator account is disabled.

1. (Optional) Specify settings in `unattend.xml` and other configuration files. If plan to attend to the installation, then you don't need to make changes in these files. The files are located in the following directory by default: `C:\ProgramData\Amazon\EC2-Windows\Launch\Sysprep`.

1. In Windows PowerShell, run `./InitializeInstance.ps1 -Schedule`. The script is located in the following directory, by default: `C:\ProgramData\Amazon\EC2-Windows\Launch\Scripts`. This script schedules the instance to initialize during the next boot. You must run this script before you run the `SysprepInstance.ps1` script in the next step.

1. In Windows PowerShell, run `./SysprepInstance.ps1`. The script is located in the following directory by default: `C:\ProgramData\Amazon\EC2-Windows\Launch\Scripts`. 

You are logged off the instance and the instance shuts down. If you check the **Instances** page in the Amazon EC2 console, the instance state changes from `Running` to `Stopping`, and then to `Stopped`. At this point, it is safe to create an AMI from this instance.

## Update metadata/KMS routes for Server 2016 and later when launching a custom AMI


To update metadata/KMS routes for Server 2016 and later when launching a custom AMI, do one of the following:
+ Run the EC2LaunchSettings GUI (C:\$1ProgramData\$1Amazon\$1EC2-Windows\$1Launch\$1Settings\$1Ec2LaunchSettings.exe) and select the option to shut down with Windows Sysprep.
+ Run EC2LaunchSettings and shut down without Windows Sysprep before creating the AMI. This sets the EC2 Launch Initialize tasks to run at the next boot, which will set routes based on the subnet for the instance.
+ Manually reschedule EC2 Launch initialize tasks before creating an AMI from [PowerShell](ec2launch-config.md#ec2launch-inittasks). 
**Important**  
Take note of the default password reset behavior before rescheduling tasks.
+ To update the routes on a running instance that is experiencing Windows activation or communication with instance metadata failures, see ["Unable to activate Windows"](common-messages.md#activate-windows).

# Create an AMI using Windows Sysprep with EC2Config
Use Windows Sysprep with EC2Config

When you create an image from an instance with the EC2Config service installed, EC2Config performs specific tasks as the image is prepared. This includes working with Windows Sysprep. For more information, see [Windows Sysprep phases](ami-create-win-sysprep.md#sysprep-phases).

**Topics**
+ [

## Windows Sysprep actions
](#sysprep-actions)
+ [

## Post Sysprep
](#sysprep-post)
+ [

## Run Windows Sysprep with the EC2Config service
](#sysprep-gui-procedure)

## Windows Sysprep actions


Windows Sysprep and the EC2Config service perform the following actions when preparing an image.

1. When you choose **Shutdown with Sysprep** in the **EC2 Service Properties** dialog box, the system runs the **ec2config.exe -sysprep** command.

1. The EC2Config service reads the content of the `BundleConfig.xml` file. This file is located in the following directory, by default: `C:\Program Files\Amazon\Ec2ConfigService\Settings`.

    The `BundleConfig.xml` file includes the following settings. You can change these settings:
   + **AutoSysprep**: Indicates whether to use Windows Sysprep automatically. You do not need to change this value if you are running Windows Sysprep from the EC2 Service Properties dialog box. The default value is `No`.
   + **SetRDPCertificate**: Sets a self-signed certificate for the Remote Desktop server. This enables you to securely use the Remote Desktop Protocol (RDP) to connect to the instance. Change the value to `Yes` if new instances should use a certificate. This setting is not used with Windows Server 2012 instances because these operating systems can generate their own certificates. The default value is `No`.
   + **SetPasswordAfterSysprep**: Sets a random password on a newly launched instance, encrypts it with the user launch key, and outputs the encrypted password to the console. Change the value to `No` if new instances should not be set to a random encrypted password. The default value is `Yes`.
   +  **PreSysprepRunCmd**: The location of the command to run. The command is located in the following directory, by default: `C:\Program Files\Amazon\Ec2ConfigService\Scripts\BeforeSysprep.cmd`

1. The system runs `BeforeSysprep.cmd`. This command creates a registry key as follows:

   ```
   reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 1 /f
   ```

   The registry key disables RDP connections until they are re-enabled. Disabling RDP connections is a necessary security measure because, during the first boot session after Windows Sysprep has run, there is a short period of time where RDP allows connections and the Administrator password is blank.

1. The EC2Config service calls Windows Sysprep by running the following command:

   ```
   sysprep.exe /unattend: "C:\Program Files\Amazon\Ec2ConfigService\sysprep2008.xml" /oobe /generalize /shutdown
   ```

### Generalize phase

+ The tool removes image-specific information and configurations such as the computer name and the SID. If the instance is a member of a domain, it is removed from the domain. The `sysprep2008.xml` answer file includes the following settings that affect this phase: 
  + **PersistAllDeviceInstalls**: This setting prevents Windows Setup from removing and reconfiguring devices, which speeds up the image preparation process because Amazon AMIs require certain drivers to run and re-detection of those drivers would take time.
  + **DoNotCleanUpNonPresentDevices**: This setting retains Plug and Play information for devices that are not currently present.
+ Windows Sysprep shuts down the OS as it prepares to create the AMI. The system either launches a new instance or starts the original instance.

### Specialize phase


The system generates OS specific requirements such as a computer name and a SID. The system also performs the following actions based on configurations that you specify in the sysprep2008.xml answer file.
+ **CopyProfile**: Windows Sysprep can be configured to delete all user profiles, including the built-in Administrator profile. This setting retains the built-in Administrator account so that any customizations you made to that account are carried over to the new image. The default value is True.

  **CopyProfile** replaces the default profile with the existing local administrator profile. All accounts logged into after running Windows Sysprep will receive a copy of that profile and its contents at first login. 

  If you don’t have specific user-profile customizations that you want to carry over to the new image then change this setting to False. Windows Sysprep will remove all user profiles; this saves time and disk space. 
+ **TimeZone**: The time zone is set to Coordinate Universal Time (UTC) by default.
+ **Synchronous command with order 1**: The system runs the following command that enables the administrator account and specifies the password requirement.

  **net user Administrator /ACTIVE:YES /LOGONPASSWORDCHG:NO /EXPIRES:NEVER /PASSWORDREQ:YES**
+ **Synchronous command with order 2**: The system scrambles the administrator password. This security measure is designed to prevent the instance from being accessible after Windows Sysprep completes if you did not enable the ec2setpassword setting.

  C:\$1Program Files\$1Amazon\$1Ec2ConfigService\$1ScramblePassword.exe" -u Administrator
+ **Synchronous command with order 3**: The system runs the following command:

  C:\$1Program Files\$1Amazon\$1Ec2ConfigService\$1Scripts\$1SysprepSpecializePhase.cmd

   This command adds the following registry key, which re-enables RDP:

  reg add "HKEY\$1LOCAL\$1MACHINE\$1SYSTEM\$1CurrentControlSet\$1Control\$1Terminal Server" /v fDenyTSConnections /t REG\$1DWORD /d 0 /f

### OOBE phase


1. Using the EC2Config service answer file, the system specifies the following configurations:
   + <InputLocale>en-US</InputLocale>
   + <SystemLocale>en-US</SystemLocale>
   + <UILanguage>en-US</UILanguage>
   + <UserLocale>en-US</UserLocale>
   + <HideEULAPage>true</HideEULAPage>
   + <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE>
   + <NetworkLocation>Other</NetworkLocation>
   + <ProtectYourPC>3</ProtectYourPC>
   + <BluetoothTaskbarIconEnabled>false</BluetoothTaskbarIconEnabled>
   + <TimeZone>UTC</TimeZone>
   + <RegisteredOrganization>Amazon.com</RegisteredOrganization>
   + <RegisteredOwner>Amazon</RegisteredOwner>
**Note**  
During the generalize and specialize phases the EC2Config service monitors the status of the OS. If EC2Config detects that the OS is in a Sysprep phase, then it publishes the following message to the system log:  
EC2ConfigMonitorState: 0 Windows is being configured. SysprepState=IMAGE\$1STATE\$1UNDEPLOYABLE

1. After the OOBE phase completes, the system runs `SetupComplete.cmd` from the following location: `C:\Windows\Setup\Scripts\SetupComplete.cmd`. In Amazon public AMIs before April 2015 this file was empty and ran nothing on the image. In public AMIs dated after April 2015, the file includes the following value: **call "C:\$1Program Files\$1Amazon\$1Ec2ConfigService\$1Scripts\$1PostSysprep.cmd"**.

1. The system runs `PostSysprep.cmd`, which performs the following operations:
   + Sets the local Administrator password to not expire. If the password expired, Administrators might not be able to log on.
   + Sets the MSSQLServer machine name (if installed) so that the name will be in sync with the AMI.

## Post Sysprep


After Windows Sysprep completes, the EC2Config services sends the following message to the console output:

```
Windows sysprep configuration complete.
			Message: Sysprep Start
			Message: Sysprep End
```

EC2Config then performs the following actions:

1. Reads the content of the config.xml file and lists all enabled plug-ins. 

1. Executes all “Before Windows is ready” plug-ins at the same time.
   + Ec2SetPassword
   + Ec2SetComputerName
   + Ec2InitializeDrives
   + Ec2EventLog
   + Ec2ConfigureRDP
   + Ec2OutputRDPCert
   + Ec2SetDriveLetter
   + Ec2WindowsActivate
   + Ec2DynamicBootVolumeSize

1. After it is finished, sends a “Windows is ready” message to the instance system logs.

1. Runs all “After Windows is ready” plug-ins at the same time.
   + Amazon CloudWatch Logs 
   + UserData
   + AWS Systems Manager (Systems Manager) 

For more information about Windows plug-ins, see [Use the EC2Config service to perform tasks during EC2 legacy Windows operating system instance launch](ec2config-service.md).

## Run Windows Sysprep with the EC2Config service


Use the following procedure to create a standardized AMI using Windows Sysprep and the EC2Config service.

1. In the Amazon EC2 console, locate or [create](creating-an-ami-ebs.md) an AMI that you want to duplicate.

1. Launch and connect to your Windows instance.

1. Customize it.

1. Specify configuration settings in the EC2Config service answer file:

   `C:\Program Files\Amazon\Ec2ConfigService\sysprep2008.xml`

1. From the Windows **Start** menu, choose **All Programs**, and then choose **EC2ConfigService Settings**. 

1. Choose the **Image** tab in the **Ec2 Service Properties** dialog box. For more information about the options and settings in the Ec2 Service Properties dialog box, see [Ec2 Service Properties](ec2config-service.md).

1. Select an option for the Administrator password, and then select **Shutdown with Sysprep** or **Shutdown without Sysprep**. EC2Config edits the settings files based on the password option that you selected.
   + **Random**: EC2Config generates a password, encrypts it with user's key, and displays the encrypted password to the console. We disable this setting after the first launch so that this password persists if the instance is rebooted or stopped and started.
   + **Specify**: The password is stored in the Windows Sysprep answer file in unencrypted form (clear text). When Windows Sysprep runs next, it sets the Administrator password. If you shut down now, the password is set immediately. When the service starts again, the Administrator password is removed. It's important to remember this password, as you can't retrieve it later.
   + **Keep Existing**: The existing password for the Administrator account doesn't change when Windows Sysprep is run or EC2Config is restarted. It's important to remember this password, as you can't retrieve it later.

1. Choose **OK**.

When you are asked to confirm that you want to run Windows Sysprep and shut down the instance, click **Yes**. You'll notice that EC2Config runs Windows Sysprep. Next, you are logged off the instance, and the instance is shut down. If you check the **Instances** page in the Amazon EC2 console, the instance state changes from `Running` to `Stopping`, and then finally to `Stopped`. At this point, it's safe to create an AMI from this instance.

You can manually invoke the Windows Sysprep tool from the command line using the following command:

```
"%programfiles%\amazon\ec2configservice\"ec2config.exe -sysprep"" 
```

**Note**  
The double quotation marks in the command are not required if your CMD shell is already in the C:\$1Program Files\$1Amazon\$1EC2ConfigService\$1 directory.

However, you must be very careful that the XML file options specified in the `Ec2ConfigService\Settings` folder are correct; otherwise, you might not be able to connect to the instance. For more information about the settings files, see [EC2Config settings files](ec2config-service.md#UsingConfigXML_WinAMI). For an example of configuring and then running Windows Sysprep from the command line, see `Ec2ConfigService\Scripts\InstallUpdates.ps1`.

# Copy an Amazon EC2 AMI
Copy an AMI

When you need a consistent Amazon EC2 instance configuration across multiple Regions, you can use a single Amazon Machine Image (AMI) as your template to launch all the instances. However, AMIs are Region-specific resources—to launch an instance in a specific AWS Region, the AMI must be located in that Region. Therefore, to use the same AMI in multiple Regions, you must copy it from the source Region to each target Region.

The method you use to copy an AMI depends on whether you're copying across Regions *within the same [partition](https://docs.aws.amazon.com/glossary/latest/reference/glos-chap.html#partition)* or *across different partitions*:
+ **Cross-Region copying** – Copy AMIs across Regions *within the same partition*, for example, across the Regions within the commercial partition. This copy method is described in this topic.
+ **Cross-partition copying** – Copy AMIs *from one partition to another partition*, for example, from the commercial partition to the AWS GovCloud (US) partition. For information about this copy method, see [Store and restore an AMIAllowed AMIs](ami-store-restore.md).
+ **Cross-account copying** – Create a copy of an AMI that another AWS account has [shared with your AWS account](sharingamis-explicit.md). This copy method is described in this topic.

The time taken to complete the copy operation for cross-Region and cross-account AMI copying is on a best-effort basis. If you need control over the completion time, you can specify a completion window ranging from 15 minutes to 48 hours, ensuring your AMI is copied within your required timeframe. Additional charges apply for time-based AMI copy operations. For more information, see [Time-based copies](https://docs.aws.amazon.com/ebs/latest/userguide/time-based-copies.html) in the *Amazon EBS User Guide*.

**Topics**
+ [

## Considerations
](#copy-ami-considerations)
+ [

## Costs
](#copy-ami-costs)
+ [

# Grant permissions to copy Amazon EC2 AMIs
](copy-ami-permissions.md)
+ [

## Copy an AMI
](#ami-copy-steps)
+ [

## Stop a pending AMI copy operation
](#ami-copy-stop)
+ [

# How Amazon EC2 AMI copy works
](how-ami-copy-works.md)

## Considerations

+ **Permission to copy AMIs** – You can use IAM policies to grant or deny users permission to copy AMIs. Starting October 28, 2024, you can specify resource-level permissions for the `CopyImage` action on the source AMI. Resource-level permissions for the new AMI are available as before.
+ **Launch permissions and Amazon S3 bucket permissions** – AWS does not copy launch permissions or Amazon S3 bucket permissions from the source AMI to the new AMI. After the copy operation is complete, you can apply launch permissions and Amazon S3 bucket permissions to the new AMI.
+ **Tags** – You can only copy user-defined AMI tags that you attached to the source AMI. System tags (prefixed with `aws:`) and user-defined tags that are attached by other AWS accounts will not be copied. When copying an AMI, you can attach new tags to the new AMI and its backing snapshots.
+ **Quotas for time-based AMI copies** – After you reach your *cumulative snapshot copy throughput quota*, subsequent time-based AMI copy requests fail. For more information, see [Quotas for time-based copies](https://docs.aws.amazon.com/ebs/latest/userguide/time-based-copies.html#time-based-copies-quota) in the *Amazon EBS User Guide*.
+ **Supported source-destination copies** – The location of the source AMI determines whether you can copy it and the allowed destinations for the new AMI:
  + If the source AMI is in a Region, you can copy it within that Region, to another Region, to an Outpost associated with that Region, or to a Local Zone in that Region.
  + If the source AMI is in a Local Zone, you can copy it within that Local Zone, to the parent Region of that Local Zone, or to certain other Local Zones with the same parent Region.
  + If the source AMI is on an Outpost, you can't copy it.
+ **CLI parameters for source and destination** – When using the CLI, the following parameters are supported for specifying the source location of the AMI to copy and the destination of the new AMI. Note that the copy operation must be initiated in the destination Region; if you omit the `--region` parameter, the destination assumes the default Region configured in your AWS CLI settings.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/CopyingAMIs.html)

## Costs


There is no charge for copying an AMI when no completion time is specified. However, additional charges apply for time-based AMI copy operations. For more information, see [Time-based copies](https://docs.aws.amazon.com/ebs/latest/userguide/time-based-copies.html#time-based-copies-pricing) in the *Amazon EBS User Guide*.

Standard storage and data transfer rates apply. If you copy an EBS-backed AMI, you will incur charges for the storage of any additional EBS snapshots.

# Grant permissions to copy Amazon EC2 AMIs
Permissions

To copy an EBS-backed or Amazon S3-backed AMI, you need the following IAM permissions:
+ `ec2:CopyImage` – To copy the AMI. For EBS-backed AMIs, it also grants permission to copy the AMI's backing snapshots.
+ `ec2:CreateTags` – To tag the target AMI. For EBS-backed AMIs, it also grants permission to tag the target AMI’s backing snapshots.

If you're copying an instance stored-backed AMI, you need the following *additional* IAM permissions:
+ `s3:CreateBucket` – To create the S3 bucket in the target Region for the new AMI
+ `s3:PutBucketOwnershipControls` – To enable ACLs for the newly created S3 bucket so that objects can be written with the `aws-exec-read` [canned ACL](https://docs.aws.amazon.com/AmazonS3/latest/userguide/acl-overview.html#canned-acl)
+ `s3:GetBucketAcl` – To read the ACLs for the source bucket
+ `s3:ListAllMyBuckets` – To find an existing S3 bucket for AMIs in the target Region
+ `s3:GetObject` – To read the objects in the source bucket
+ `s3:PutObject` – To write the objects in the target bucket
+ `s3:PutObjectAcl` – To write the permissions for the new objects in the target bucket

**Note**  
Starting October 28, 2024, you can specify resource-level permissions for the `CopyImage` action on the source AMI. Resource-level permissions for the target AMI are available as before. For more information, see **CopyImage** in the table under [Actions defined by Amazon EC2](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonec2.html#amazonec2-actions-as-permissions) in the *Service Authorization Reference*.

## Example IAM policy for copying an EBS-backed AMI and tagging the target AMI and snapshots


The following example policy grants you permission to copy any EBS-backed AMI and tag the target AMI and its backing snapshots.

**Note**  
Starting October 28, 2024, you can specify snapshots in the `Resource` element. For more information, see **CopyImage** in the table under [Actions defined by Amazon EC2](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonec2.html#amazonec2-actions-as-permissions) in the *Service Authorization Reference*.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [{
        "Sid": "PermissionToCopyAllImages",
        "Effect": "Allow",
        "Action": [
            "ec2:CopyImage",
            "ec2:CreateTags"
        ],
        "Resource": [
            "arn:aws:ec2:*::image/*",
            "arn:aws:ec2:*::snapshot/*"
        ]
    }]
}
```

------

## Example IAM policy for copying an EBS-backed AMI but denying tagging the new snapshots


The `ec2:CopySnapshot` permission is automatically granted when you get the `ec2:CopyImage` permission. Permission to tag the new backing snapshots can be explicitly denied, overriding the `Allow` effect for the `ec2:CreateTags` action.

The following example policy grants you permission to copy any EBS-backed AMI, but denies you from tagging the new backing snapshots of the target AMI.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [{
            "Effect": "Allow",
            "Action": [
                "ec2:CopyImage",
                "ec2:CreateTags"
            ],
            "Resource": [
                "arn:aws:ec2:*::image/*",
                "arn:aws:ec2:*::snapshot/*"
            ]
        },
        {
            "Effect": "Deny",
            "Action": "ec2:CreateTags",
            "Resource": "arn:aws:ec2:::snapshot/*"
        }
    ]
}
```

------

## Example IAM policy for copying an Amazon S3-backed AMI and tagging the target AMI


The following example policy grants you permission to copy any Amazon S3-backed AMI in the specified source bucket to the specified Region, and tag the target AMI.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [{
            "Sid": "PermissionToCopyAllImages",
            "Effect": "Allow",
            "Action": [
                "ec2:CopyImage",
                "ec2:CreateTags"
            ],
            "Resource": "arn:aws:ec2:*::image/*"
        },
        {
            "Effect": "Allow",
            "Action": "s3:ListAllMyBuckets",
            "Resource": [
                "arn:aws:s3:::*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": "s3:GetObject",
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-source-bucket/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:CreateBucket",
                "s3:GetBucketAcl",
                "s3:PutObjectAcl",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::amis-for-111122223333-in-us-east-2-hash"
            ]
        }
    ]
}
```

------

To find the Amazon Resource Name (ARN) of the AMI source bucket, open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/), in the navigation pane choose **AMIs**, and locate the bucket name in the **Source** column.

**Note**  
The `s3:CreateBucket` permission is only needed the first time that you copy an Amazon S3-backed AMI to an individual Region. After that, the Amazon S3 bucket that is already created in the Region is used to store all future AMIs that you copy to that Region.

## Copy an AMI


You can copy an AMI that you own or an AMI that was shared with you from another account. For the supported source and destination combinations, see [Considerations](#copy-ami-considerations).

------
#### [ Console ]

**To copy an AMI**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. From the console navigation bar, select the Region that contains the AMI.

1. In the navigation pane, choose **AMIs** to display the list of AMIs available to you in the Region.

1. If you don't see the AMI you want to copy, choose a different filter. You can filter by AMIs **Owned by me**, **Private images**, **Public images**, and **Disabled images**.

1. Select the AMI to copy, and then choose **Actions**, **Copy AMI**.

1. On the **Copy Amazon Machine Image (AMI)** page, specify the following information:

   1. **AMI copy name**: A name for the new AMI. You can include the operating system information in the name because Amazon EC2 does not provide this information when displaying details about the AMI.

   1. **AMI copy description**: By default, the description includes information about the source AMI so that you can distinguish a copy from its original. You can change this description as needed.

   1. **Destination Region**: The Region in which to copy the AMI. For more information, see [Cross-Region copying](how-ami-copy-works.md#copy-amis-across-regions) and [Cross-account copying](how-ami-copy-works.md#copy-ami-across-accounts).

   1. **Copy tags**: Select this checkbox to include your user-defined AMI tags when copying the AMI. System tags (prefixed with `aws:`) and user-defined tags that are attached by other AWS accounts will not be copied.

   1. **Time-based copy**: You can specify whether the copy operation completes within a specific timeframe or on a best-effort basis, as follows:
      + To complete the copy within a specific timeframe:
        + Select **Enable time-based copy**.
        + For **Completion duration**, enter the number of minutes (in 15-minute increments) allowed for the copy operation. The completion duration applies to all snapshots associated with the AMI.

          For more information, see [Time-based copies](https://docs.aws.amazon.com/ebs/latest/userguide/time-based-copies.html) in the *Amazon EBS User Guide*.
      + To complete the copy on a best-effort basis:
        + Leave **Enable time-based copy** unselected.

   1. (EBS-backed AMIs only) **Encrypt EBS snapshots of AMI copy**: Select this checkbox to encrypt the target snapshots, or to re-encrypt them using a different key. If encryption by default is enabled, the **Encrypt EBS snapshots of AMI copy** checkbox is selected and cannot be cleared. For more information, see [Encryption and copying](how-ami-copy-works.md#ami-copy-encryption).

   1. (EBS-backed AMIs only) **KMS key**: The KMS key to used to encrypt the target snapshots.

   1. **Tags**: You can tag the new AMI and the new snapshots with the same tags, or you can tag them with different tags.
      + To tag the new AMI and the new snapshots with the *same* tags, choose **Tag image and snapshots together**. The same tags are applied to the new AMI and every snapshot that is created.
      + To tag the new AMI and the new snapshots with *different* tags, choose **Tag image and snapshots separately**. Different tags are applied to the new AMI and the snapshots that are created. Note, however, that all the new snapshots that are created get the same tags; you can't tag each new snapshot with a different tag.

      To add a tag, choose **Add tag**, and enter the key and value for the tag. Repeat for each tag.

   1. When you're ready to copy the AMI, choose **Copy AMI**.

      The initial status of the new AMI is `Pending`. The AMI copy operation is complete when the status is `Available`.

------
#### [ AWS CLI ]

**To copy an AMI from one Region to another Region**  
Use the [copy-image](https://docs.aws.amazon.com/cli/latest/reference/ec2/copy-image.html) command. You must specify both the source and destination Regions. You specify the source Region using the `--source-region` parameter. You can specify the destination Region using the `--region` parameter (or omit this parameter to assume the default Region configured in your AWS CLI settings).

```
aws ec2 copy-image \
    --source-image-id ami-0abcdef1234567890 \
    --source-region us-west-2 \
    --name my-ami \
    --region us-east-1
```

When you encrypt a target snapshot during AMI copy, you must specify these additional parameters: `--encrypted` and `--kms-key-id`.

**To copy an AMI from a Region to a Local Zone**  
Use the [copy-image](https://docs.aws.amazon.com/cli/latest/reference/ec2/copy-image.html) command. You must specify both the source and destination. You specify the source Region using the `--source-region` parameter. You specify the destination Local Zone using the `--destination-availability-zone` parameter (you can use `--destination-availability-zone-id` instead). Note that you can only copy an AMI from a Region to a Local Zone within that same Region.

```
aws ec2 copy-image \
    --source-image-id ami-0abcdef1234567890 \
    --source-region cn-north-1 \
    --destination-availability-zone cn-north-1-pkx-1a \
    --name my-ami \
    --region cn-north-1
```

**To copy an AMI from a Local Zone to a Region**  
Use the [copy-image](https://docs.aws.amazon.com/cli/latest/reference/ec2/copy-image.html) command. You must specify both the source and destination. You specify the source Region using the `--source-region` parameter. You specify the destination Region using the `--region` parameter (or omit this parameter to assume the default Region configured in your AWS CLI settings). The source Local Zone is assumed from the location of the specified source AMI ID. Note that you can only copy an AMI from a Local Zone to its parent Region.

```
aws ec2 copy-image \
    --source-image-id ami-0abcdef1234567890 \
    --source-region cn-north-1 \
    --name my-ami \
    --region cn-north-1
```

**To copy an AMI from one Local Zone to another Local Zone**  
Use the [copy-image](https://docs.aws.amazon.com/cli/latest/reference/ec2/copy-image.html) command. You must specify both the source and destination. You specify the source Region of the Local Zone using the `--source-region` parameter. You specify the destination Local Zone using the `--destination-availability-zone` parameter (you can use `--destination-availability-zone-id` instead). The source Local Zone is assumed from the location of the specified source AMI ID. You specify the parent Region of the destination Local Zone using the `--region` parameter (or omit this parameter to assume the default Region configured in your AWS CLI settings).

```
aws ec2 copy-image \
    --source-image-id ami-0abcdef1234567890 \
    --source-region cn-north-1 \
    --destination-availability-zone cn-north-1-pkx-1a \
    --name my-ami \
    --region cn-north-1
```

------
#### [ PowerShell ]

**To copy an AMI from one Region to another Region**  
Use the [Copy-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Copy-EC2Image.html) cmdlet. You must specify both the source and destination Regions. You specify the source Region using the `-SourceRegion` parameter. You can specify the destination Region using the `-Region` parameter or the [Set-AWSDefaultRegion](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-installing-specifying-region.html) cmdlet.

```
Copy-EC2Image `
    -SourceImageId ami-0abcdef1234567890 `
    -SourceRegion us-west-2 `
    -Name my-ami `
    -Region us-east-1
```

When you encrypt a target snapshot during AMI copy, you must specify these additional parameters: `-Encrypted` and `-KmsKeyId`.

**To copy an AMI from a Region to a Local Zone**  
Use the [Copy-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Copy-EC2Image.html) cmdlet. You must specify both the source and destination. You specify the source Region using the `-SourceRegion` parameter. You specify the destination Local Zone using the `-DestinationAvailabilityZone` parameter (you can use `-DestinationAvailabilityZoneId` instead). Note that you can only copy an AMI from a Region to a Local Zone within that same Region.

```
Copy-EC2Image `
    -SourceImageId ami-0abcdef1234567890 `
    -SourceRegion cn-north-1 `
    -DestinationAvailabilityZone cn-north-1-pkx-1a `
    -Name my-ami `
    -Region cn-north-1
```

**To copy an AMI from a Local Zone to a Region**  
Use the [Copy-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Copy-EC2Image.html) cmdlet. You must specify both the source and destination. You specify the source Region using the `-SourceRegion` parameter. You specify the destination Region using the `-Region` parameter or the [Set-AWSDefaultRegion](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-installing-specifying-region.html) cmdlet. The source Local Zone is assumed from the location of the specified source AMI ID. Note that you can only copy an AMI from a Local Zone to its parent Region.

```
Copy-EC2Image `
    -SourceImageId ami-0abcdef1234567890 `
    -SourceRegion cn-north-1 `
    -Name my-ami `
    -Region cn-north-1
```

**To copy an AMI from one Local Zone to another Local Zone**  
Use the [Copy-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Copy-EC2Image.html) cmdlet. You must specify both the source and destination. You specify the source Region of the Local Zone using the `-SourceRegion` parameter. You specify the destination Local Zone using the `-DestinationAvailabilityZone` parameter (you can use `-DestinationAvailabilityZoneId` instead). The source Local Zone is assumed from the location of the specified source AMI ID. You specify the parent Region of the destination Local Zone using the `-Region` parameter or the [Set-AWSDefaultRegion](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-installing-specifying-region.html) cmdlet.

```
Copy-EC2Image `
    -SourceImageId ami-0abcdef1234567890 `
    -SourceRegion cn-north-1 `
    -DestinationAvailabilityZone cn-north-1-pkx-1a `
    -Name my-ami `
    -Region cn-north-1
```

------

## Stop a pending AMI copy operation


You can stop a pending AMI copy using the following procedures.

------
#### [ Console ]

**To stop an AMI copy operation**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. From the navigation bar, select the destination Region from the Region selector.

1. In the navigation pane, choose **AMIs**.

1. Select the AMI to stop copying, and then choose **Actions**, **Deregister AMI**.

1. When asked for confirmation, choose **Deregister AMI**.

------
#### [ AWS CLI ]

**To stop an AMI copy operation**  
Use the [deregister-image](https://docs.aws.amazon.com/cli/latest/reference/ec2/deregister-image.html) command.

```
aws ec2 deregister-image --image-id ami-0abcdef1234567890
```

------
#### [ PowerShell ]

**To stop an AMI copy operation using**  
Use the [Unregister-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Unregister-EC2Image.html) cmdlet.

```
Unregister-EC2Image -ImageId ami-0abcdef1234567890
```

------

# How Amazon EC2 AMI copy works
How AMI copy works

Copying a source AMI results in an identical but distinct new AMI that we also refer to as the *target* AMI. The target AMI has its own unique AMI ID. You can change or deregister the source AMI with no effect on the target AMI. The reverse is also true.

With an EBS-backed AMI, each of its backing snapshots is copied to an identical but distinct target snapshot. If you copy an AMI to a new Region, the snapshots are complete (non-incremental) copies. If you encrypt unencrypted backing snapshots or encrypt them to a new KMS key, the snapshots are complete (non-incremental) copies. Subsequent copy operations of an AMI result in incremental copies of the backing snapshots.

**Topics**
+ [

## Cross-Region copying
](#copy-amis-across-regions)
+ [

## Cross-account copying
](#copy-ami-across-accounts)
+ [

## Time-based AMI copy operations
](#ami-time-based)
+ [

## Encryption and copying
](#ami-copy-encryption)

## Cross-Region copying


Copying an AMI across geographically diverse Regions provides the following benefits:
+ Consistent global deployment: Copying an AMI from one Region to another enables you to launch consistent instances in different Regions based on the same AMI.
+ Scalability: You can more easily design and build global applications that meet the needs of your users, regardless of their location.
+ Performance: You can increase performance by distributing your application, as well as locating critical components of your application in closer proximity to your users. You can also take advantage of Region-specific features, such as instance types or other AWS services.
+ High availability: You can design and deploy applications across AWS Regions, to increase availability.

The following diagram shows the relationship between a source AMI and two copied AMIs in different Regions, as well as the EC2 instances launched from each. When you launch an instance from an AMI, it resides in the same Region where the AMI resides. If you make changes to the source AMI and want those changes to be reflected in the AMIs in the target Regions, you must recopy the source AMI to the target Regions.

![\[AMIs copied in different Regions\]](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/images/ami_copy.png)


When you first copy an Amazon S3-backed AMI to a Region, we create an Amazon S3 bucket for the AMIs copied to that Region. All Amazon S3-backed AMIs that you copy to that Region are stored in this bucket. The bucket names have the following format: amis-for-*account*-in-*region*-*hash*. For example: `amis-for-123456789012-in-us-east-2-yhjmxvp6`.

**Prerequisite**  
Prior to copying an AMI, you must ensure that the contents of the source AMI are updated to support running in a different Region. For example, you should update any database connection strings or similar application configuration data to point to the appropriate resources. Otherwise, instances launched from the new AMI in the destination Region might still use the resources from the source Region, which can impact performance and cost.

**Limitations**
+ Destination Regions are limited to 300 concurrent AMI copy operations. This also applies to time-based AMI copy operations.
+ You can't copy a paravirtual (PV) AMI to a Region that does not support PV AMIs. For more information, see [Virtualization types](ComponentsAMIs.md#virtualization_types).

## Cross-account copying


If an AMI from another AWS account is [shared with your AWS account](sharingamis-explicit.md), you can copy the shared AMI. This is known as cross-account copying. The AMI that is shared with you is the source AMI. When you copy the source AMI, you create a new AMI. The new AMI is often referred to as the target AMI.

**AMI costs**
+ For a shared AMI, the account of the shared AMI is charged for the storage in the Region.
+ If you copy an AMI that is shared with your account, you are the owner of the target AMI in your account.
  + The owner of the source AMI is charged standard Amazon EBS or Amazon S3 transfer fees.
  + You are charged for the storage of the target AMI in the destination Region.

**Resource permissions**  
To copy an AMI that was shared with you from another account, the owner of the source AMI must grant you read permissions for the storage that backs the AMI, not just for the AMI itself. The storage is either the associated EBS snapshot (for an Amazon EBS-backed AMI) or an associated S3 bucket (for an Amazon S3-backed AMI). If the shared AMI has encrypted snapshots, the owner must share the key or keys with you. For more information about granting resource permissions, for EBS snapshots, see [Share an Amazon EBS snapshot with other AWS accounts](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-modifying-snapshot-permissions.html) in the *Amazon EBS User Guide*, and for S3 buckets, see [Identity and access management for Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/security-iam.html) in the *Amazon S3 User Guide*.

**Note**  
Tags that are attached to the source AMI are not copied across accounts to the target AMI.

## Time-based AMI copy operations


When you initiate a time-based AMI copy operation for an EBS-backed AMI with a single associated snapshot, it behaves in the same way as an **individual time-based snapshot copy operation**, and the same throughput limitations apply.

When you initiate a time-based AMI copy operation for an EBS-backed AMI with a multiple associated snapshots, it behaves in the same way as **concurrent time-based snapshot copy operations**, and the same throughput limitations apply. Each associated snapshot results in a separate snapshot copy request, each of which contributes to your cumulative snapshot copy throughput quota. The completion duration that you specify applies to each associated snapshot.

For more information, see [ Time-based copies](https://docs.aws.amazon.com/ebs/latest/userguide/time-based-copies.html) in the *Amazon EBS User Guide*.

## Encryption and copying


The following table shows encryption support for various AMI-copying scenarios. While it is possible to copy an unencrypted snapshot to yield an encrypted snapshot, you cannot copy an encrypted snapshot to yield an unencrypted one.


| Scenario | Description | Supported | 
| --- | --- | --- | 
| 1 | Unencrypted to unencrypted | Yes | 
| 2 | Encrypted to encrypted | Yes | 
| 3 | Unencrypted to encrypted | Yes | 
| 4 | Encrypted to unencrypted | No | 

**Note**  
Encrypting during the `CopyImage` action applies only to Amazon EBS-backed AMIs. Because an Amazon S3-backed AMI does not use snapshots, you can't use copying to change its encryption status.

When you copy an AMI without specifying encryption parameters, the backing snapshot is copied with its original encryption status by default. Therefore, if the source AMI is backed by an unencrypted snapshot, the resulting target snapshot will also be unencrypted. Similarly, if the source AMI's snapshot is encrypted, the resulting target snapshot will also be encrypted by the same AWS KMS key. For AMIs backed by multiple snapshots, each target snapshot preserves the encryption state of its corresponding source snapshot.

To change the encryption state of the target backing snapshots during an AMI copy, you can specify encryption parameters. The following example shows a non-default case, where encryption parameters are specified with the `CopyImage` action to change the target AMI's encryption state.

**Copy an unencrypted source AMI to an encrypted target AMI**

In this scenario, an AMI backed by an unencrypted root snapshot is copied to an AMI with an encrypted root snapshot. The `CopyImage` action is invoked with two encryption parameters, including a customer managed key. As a result, the encryption status of the root snapshot changes, so that the target AMI is backed by a root snapshot containing the same data as the source snapshot, but encrypted using the specified key. You incur storage costs for the snapshots in both AMIs, as well as charges for any instances you launch from either AMI.

**Note**  
Enabling encryption by default has the same effect as setting the `Encrypted` parameter to `true` for all snapshots in the AMI.

![\[Copy AMI and encrypt snapshot on the fly\]](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/images/ami-to-ami-convert.png)


Setting the `Encrypted` parameter encrypts the single snapshot for this instance. If you do not specify the `KmsKeyId` parameter, the default customer managed key is used to encrypt the snapshot copy.

For more information about copying AMIs with encrypted snapshots, see [Use encryption with EBS-backed AMIs](AMIEncryption.md).

# Store and restore an AMI using S3
Store and restore an AMI

You can store an Amazon Machine Image (AMI) in an Amazon S3 bucket, copy the AMI to another S3 bucket, and then restore it from the S3 bucket. By storing and restoring an AMI using S3 buckets, you can copy AMIs from one AWS partition to another, for example, from the main commercial partition to the AWS GovCloud (US) partition. You can also make archival copies of AMIs by storing them in an S3 bucket.

The supported APIs for storing and restoring an AMI using S3 are `CreateStoreImageTask`, `DescribeStoreImageTasks`, and `CreateRestoreImageTask`.

`CopyImage` is the recommended API to use for copying AMIs *within* an AWS partition. However, `CopyImage` can’t copy an AMI to *another* partition.

For information about the AWS partitions, see *partition* on the [Amazon Resource Names (ARNs)](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html) page in the *IAM User Guide*.

**Warning**  
Ensure that you comply with all applicable laws and business requirements when moving data between AWS partitions or AWS Regions, including, but not limited to, any applicable government regulations and data residency requirements.

**Topics**
+ [

## Use cases
](#use-cases)
+ [

## Limitations
](#ami-store-restore-limitations)
+ [

## Costs
](#store-restore-costs)
+ [

# How AMI store and restore works
](store-restore-how-it-works.md)
+ [

# Create a store image task
](work-with-ami-store-restore.md)

## Use cases


**Topics**
+ [

### Copy an AMI between AWS partitions
](#copy-to-partition)
+ [

### Make archival copies of AMIs
](#archival-copies)

### Copy an AMI between AWS partitions


By storing and restoring an AMI using S3 buckets, you can copy an AMI from one AWS partition to another, or from one AWS Region to another. In the following example, you copy an AMI from the main commercial partition to the AWS GovCloud (US) partition, specifically from the `us-east-2` Region to the `us-gov-east-1` Region.

To copy an AMI from one partition to another, follow these steps:
+ Store the AMI in an S3 bucket in the current Region by using `CreateStoreImageTask`. In this example, the S3 bucket is located in `us-east-2`.
+ Monitor the progress of the store task by using `DescribeStoreImageTasks`. The object becomes visible in the S3 bucket when the task is completed.
+ Copy the stored AMI object to an S3 bucket in the target partition using a procedure of your choice. In this example, the S3 bucket is located in `us-gov-east-1`.
**Note**  
Because you need different AWS credentials for each partition, you can’t copy an S3 object directly from one partition to another. The process for copying an S3 object across partitions is outside the scope of this documentation. We provide the following copy processes as examples, but you must use the copy process that meets your security requirements.  
To copy one AMI across partitions, the copy process could be as straightforward as the following: [Download the object](https://docs.aws.amazon.com/AmazonS3/latest/userguide/download-objects.html) from the source bucket to an intermediate host (for example, an EC2 instance or a laptop), and then [upload the object](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html) from the intermediate host to the target bucket. For each stage of the process, use the AWS credentials for the partition.
For more sustained usage, consider developing an application that manages the copies, potentially using S3 [multipart downloads and uploads](https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpuoverview.html).
+ Restore the AMI from the S3 bucket in the target partition by using `CreateRestoreImageTask`. In this example, the S3 bucket is located in `us-gov-east-1`.
+ Monitor the progress of the restore task by describing the AMI to check when its state becomes available. You can also monitor the progress percentages of the snapshots that make up the restored AMI by describing the snapshots.

### Make archival copies of AMIs


You can make archival copies of AMIs by storing them in an S3 bucket. The AMI is packed into a single object in S3, and all of the AMI metadata (excluding sharing information) is preserved as part of the stored AMI. The AMI data is compressed as part of the storage process. AMIs that contain data that can easily be compressed will result in smaller objects in S3. To reduce costs, you can use less expensive S3 storage tiers. For more information, see [Amazon S3 Storage Classes](https://aws.amazon.com/s3/storage-classes/) and [Amazon S3 pricing](https://aws.amazon.com/s3/pricing/)

## Limitations

+ To store an AMI, your AWS account must either own the AMI and its snapshots, or the AMI and its snapshots must be [shared directly with your account](sharingamis-explicit.md). You can't store an AMI if it is only [publicly shared](sharingamis-intro.md).
+ Only EBS-backed AMIs can be stored using these APIs.
+ Paravirtual (PV) AMIs are not supported.
+ The size of an AMI (before compression) that can be stored is limited to 5,000 GB.
+ Quota on store image requests: 1,200 GB of storage work (snapshot data) in progress.
+ Quota on restore image requests: 600 GB of restore work (snapshot data) in progress.
+ For the duration of the store task, the snapshots must not be deleted and the IAM principal doing the store must have access to the snapshots, otherwise the store process will fail.
+ You can’t create multiple copies of an AMI in the same S3 bucket.
+ An AMI that is stored in an S3 bucket can’t be restored with its original AMI ID. You can mitigate this by using [AMI aliasing](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-ec2-aliases.html).
+ Currently the store and restore APIs are only supported by using the AWS Command Line Interface, AWS SDKs, and Amazon EC2 API. You can’t store and restore an AMI using the Amazon EC2 console.

## Costs


When you store and restore AMIs using S3, you are charged for the services that are used by the store and restore APIs, and for data transfer. The APIs use S3 and the EBS Direct API (used internally by these APIs to access the snapshot data). For more information, see [Amazon S3 pricing](https://aws.amazon.com/s3/pricing/) and [Amazon EBS pricing](https://aws.amazon.com/ebs/pricing/).

# How AMI store and restore works


To store and restore an AMI using S3, you use the following APIs:
+ `CreateStoreImageTask` – Stores the AMI in an S3 bucket
+ `DescribeStoreImageTasks` – Provides the progress of the AMI store task
+ `CreateRestoreImageTask` – Restores the AMI from an S3 bucket

**Topics**
+ [

## CreateStoreImageTask
](#CreateStoreImageTask)
+ [

## DescribeStoreImageTasks
](#DescribeStoreImageTasks)
+ [

## CreateRestoreImageTask
](#CreateRestoreImageTask)
+ [

## File paths
](#file-paths-in-s3)

## CreateStoreImageTask


The `CreateStoreImageTask` API stores an AMI as a single object in an S3 bucket.

The API creates a task that reads all of the data from the AMI and its snapshots, and then uses an [S3 multipart upload](https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpuoverview.html) to store the data in an S3 object. The API takes all of the components of the AMI, including most of the non-Region-specific AMI metadata, and all the EBS snapshots contained in the AMI, and packs them into a single object in S3. The data is compressed as part of the upload process to reduce the amount of space used in S3, so the object in S3 might be smaller than the sum of the sizes of the snapshots in the AMI.

If there are AMI and snapshot tags visible to the account calling this API, they are preserved.

The object in S3 has the same ID as the AMI, but with a `.bin` extension. The following data is also stored as S3 metadata tags on the S3 object: AMI name, AMI description, AMI registration date, AMI owner account, and a timestamp for the store operation.

The time it takes to complete the task depends on the size of the AMI. It also depends on how many other tasks are in progress because tasks are queued. You can track the progress of the task by calling the `DescribeStoreImageTasks` API.

The sum of the sizes of all the AMIs in progress is limited to 1,200 GB of EBS snapshot data per account. Further task creation will be rejected until the tasks in progress are less than the limit. For example, if an AMI with 200 GB of snapshot data and another AMI with 400 GB of snapshot data are currently being stored, another request will be accepted, because the total in progress is 600 GB, which is less than the limit. But if a single AMI with 1,200 GB of snapshot data is currently being stored, further tasks are rejected until the task is completed.

## DescribeStoreImageTasks


The `DescribeStoreImageTasks` API describes the progress of the AMI store tasks. You can describe tasks for specified AMIs. If you don't specify AMIs, you get a paginated list of all of the store image tasks that have been processed in the last 31 days.

For each AMI task, the response indicates if the task is `InProgress`, `Completed`, or `Failed`. For tasks `InProgress`, the response shows an estimated progress as a percentage.

Tasks are listed in reverse chronological order.

Currently, only tasks from the previous month can be viewed.

## CreateRestoreImageTask


The `CreateRestoreImageTask` API starts a task that restores an AMI from an S3 object that was previously created by using a `CreateStoreImageTask` request.

The restore task can be performed in the same or a different Region in which the store task was performed.

The S3 bucket from which the AMI object will be restored must be in the same Region in which the restore task is requested. The AMI will be restored in this Region.

The AMI is restored with its metadata, such as the name, description, and block device mappings corresponding to the values of the stored AMI. The name must be unique for AMIs in the Region for this account. If you do not provide a name, the new AMI gets the same name as the original AMI. The AMI gets a new AMI ID that is generated at the time of the restore process.

The time it takes to complete the AMI restoration task depends on the size of the AMI. It also depends on how many other tasks are in progress because tasks are queued. You can view the progress of the task by describing the AMI ([describe-images](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html)) or its EBS snapshots ([describe-snapshots](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-snapshots.html)). If the task fails, the AMI and snapshots are moved to a failed state.

The sum of the sizes of all of the AMIs in progress is limited to 600 GB (based on the size after restoration) of EBS snapshot data per account. Further task creation will be rejected until the tasks in progress are less than the limit.

## File paths


You can use file paths when storing and restoring AMIs, in the following way:
+ When storing an AMI in S3, the file path can be added to the bucket name. Internally, the system separates the path from the bucket name, and then adds the path to the object key that is generated to store the AMI. The full object path is shown in the response from the API call.
+ When restoring the AMI, because an object key parameter is available, the path can be added to the beginning of the object key value.

**Example: Bucket name with appended file path**  
When you store the AMI, specify the file path after the bucket name.

```
amzn-s3-demo-bucket/path1/path2
```

The following is the resulting object key.

```
path1/path2/ami-0abcdef1234567890.bin
```

When you restore the AMI, you specify both the bucket name and the object key. For examples, see [Create a store image task](work-with-ami-store-restore.md#create-store-image-task).

# Create a store image task


When you store an AMI in an S3 bucket, a store image task is created. You can use the store image task to monitor the progress and outcome of the process.

**Topics**
+ [

## Securing your AMIs
](#securing-amis)
+ [

## Permissions for storing and restoring AMIs using S3
](#ami-s3-permissions)
+ [

## Create a store image task
](#create-store-image-task)
+ [

## Create a restore image task
](#create-restore-image-task)

## Securing your AMIs


It is important to ensure that the S3 bucket is configured with sufficient security to secure the content of the AMI and that the security is maintained for as long as the AMI objects remain in the bucket. If this can't be done, use of these APIs is not recommended. Ensure that public access to the S3 bucket is not allowed. We recommend enabling [Server-side encryption](https://docs.aws.amazon.com/AmazonS3/latest/userguide/serv-side-encryption.html) for the S3 buckets in which you store the AMIs, although it’s not required.

For information about how to set the appropriate security settings for your S3 buckets, review the following security topics:
+ [Blocking public access to your Amazon S3 storage](https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-control-block-public-access.html)
+ [Setting default server-side encryption behavior for Amazon S3 buckets](https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucket-encryption.html)
+ [What S3 bucket policy can I use to comply with the AWS Config rule s3-bucket-ssl-requests-only?](https://repost.aws/knowledge-center/s3-bucket-policy-for-config-rule)
+ [Enabling Amazon S3 server access logging](https://docs.aws.amazon.com/AmazonS3/latest/userguide/enable-server-access-logging.html)

When the AMI snapshots are copied to the S3 object, the data is then copied over TLS connections. You can store AMIs with encrypted snapshots, but the snapshots are decrypted as part of the store process.

## Permissions for storing and restoring AMIs using S3


If your IAM principals will store or restore AMIs using Amazon S3, you need to grant them the required permissions.

The following example policy includes all of the actions that are required to allow an IAM principal to carry out the store and restore tasks.

You can also create IAM policies that grant principals access to specific resources only. For more example policies, see [ Access management for AWS resources](https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html) in the *IAM User Guide*.

**Note**  
If the snapshots that make up the AMI are encrypted, or if your account is enabled for encryption by default, your IAM principal must have permission to use the KMS key.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:DeleteObject",
                "s3:GetObject",
                "s3:ListBucket",
                "s3:PutObject",
                "s3:PutObjectTagging",
                "s3:AbortMultipartUpload",
                "ebs:CompleteSnapshot",
                "ebs:GetSnapshotBlock",
                "ebs:ListChangedBlocks",
                "ebs:ListSnapshotBlocks",
                "ebs:PutSnapshotBlock",
                "ebs:StartSnapshot",
                "ec2:CreateStoreImageTask",
                "ec2:DescribeStoreImageTasks",
                "ec2:CreateRestoreImageTask",
                "ec2:GetEbsEncryptionByDefault",
                "ec2:DescribeTags",
                "ec2:CreateTags"
            ],
            "Resource": "*"
        }
    ]
}
```

------

## Create a store image task


To store an AMI in an S3 bucket, start by creating a store image task. The time it takes to complete the task depends on the size of the AMI. You can track the progress of the task until it either succeeds or fails.

------
#### [ AWS CLI ]

**To create the store image task**  
Use the [create-store-image-task](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-store-image-task.html) command.

```
aws ec2 create-store-image-task \
    --image-id ami-0abcdef1234567890 \
    --bucket amzn-s3-demo-bucket
```

The following is example output.

```
{
  "ObjectKey": "ami-0abcdef1234567890.bin"
}
```

**To describe the progress of the store image task**  
Use the [describe-store-image-tasks](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-store-image-tasks.html) command.

```
aws ec2 describe-store-image-tasks \
    --image-ids ami-0abcdef1234567890 \
    --query StoreImageTaskResults[].StoreTaskState \
    --output text
```

The following is example output.

```
InProgress
```

------
#### [ PowerShell ]

**To create the store image task**  
Use the [New-EC2StoreImageTask](https://docs.aws.amazon.com/powershell/latest/reference/items/New-EC2StoreImageTask.html) cmdlet.

```
New-EC2StoreImageTask `
    -ImageId ami-0abcdef1234567890 `
    -Bucket amzn-s3-demo-bucket
```

The following is example output.

```
ObjectKey         : ami-0abcdef1234567890.bin
```

**To describe the progress of the store image task**  
Use the [Get-EC2StoreImageTask](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2StoreImageTask.html) cmdlet.

```
(Get-EC2StoreImageTask -ImageId ami-0abcdef1234567890).StoreTaskState
```

The following is example output.

```
InProgress
```

------

## Create a restore image task


You must specify a name for the restored AMI. The name must be unique for AMIs in the Region for this account. The restored AMI gets a new AMI ID.

------
#### [ AWS CLI ]

**To create a restore image task**  
Use the [create-restore-image-task](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-restore-image-task.html) command.

```
aws ec2 create-restore-image-task \
    --object-key ami-0abcdef1234567890.bin \
    --bucket amzn-s3-demo-bucket \
    --name "my-restored-ami"
```

The following is example output.

```
{
   "ImageId": "ami-1234567890abcdef0"
}
```

------
#### [ PowerShell ]

**To create a restore image task**  
Use the [New-EC2RestoreImageTask](https://docs.aws.amazon.com/powershell/latest/reference/items/New-EC2RestoreImageTask.html) cmdlet.

```
New-EC2RestoreImageTask `
    -ObjectKey ami-0abcdef1234567890.bin `
    -Bucket amzn-s3-demo-bucket `
    -Name "my-restored-ami"
```

The following is example output.

```
ImageId         : ami-1234567890abcdef0
```

------

# Use AMI ancestry to trace the origin of an AMI
AMI ancestry

AMI ancestry helps you trace the origin of an AMI by returning the IDs and Regions of all its ancestor AMIs. When you create or copy an AMI, the new AMI retains the ID and Region of its source (parent) AMI. This enables you to track the chain of AMIs back to the root AMI.

**Key benefits**

Using AMI ancestry helps you:
+ Track AMI derivatives to ensure compliance with internal policies.
+ Identify potentially vulnerable AMIs when a security issue is found in an ancestor AMI.
+ Maintain visibility of AMI origins across multiple Regions.

**Topics**
+ [

## How AMI ancestry works
](#how-ami-ancestry-works)
+ [

## Considerations
](#ami-ancestry-conditions)
+ [

## View AMI ancestry
](#view-ami-ancestry)
+ [

## Identify the source AMI
](#identify-source-ami-used-to-create-new-ami)

## How AMI ancestry works


AMI ancestry identifies the parent AMI that was used to create the specified AMI, the parent's parent, and so on, up to the root AMI. Here's how it works:
+ Each AMI displays the ID and Region of its source (parent) AMI.
+ Starting with your selected AMI, the list of ancestry entries displays each parent AMI in sequence.
+ The list of ancestry entries traces back until it reaches the root AMI. The root AMI is one of the following: 
  + A public AMI from a [verified provider](sharing-amis.md#verified-ami-provider) (identified by its owner alias, which is either `amazon` or `aws-marketplace`).
  + An AMI with no recorded ancestor. For example, when using [RegisterImage](creating-an-ami-ebs.md#creating-launching-ami-from-snapshot) to create an AMI directly from a set of snapshots, there is no source AMI to track, unlike when creating an AMI from an instance.
  + An AMI whose source AMI is from a different [partition](https://docs.aws.amazon.com/glossary/latest/reference/glos-chap.html#partition).
  + The 50th AMI in the list. The maximum number of AMIs in an ancestry list is 50.

## Considerations

+ The ID and Region of the source AMI are only available for AMIs created using [CreateImage](creating-an-ami-ebs.md#how-to-create-ebs-ami), [CopyImage](CopyingAMIs.md#ami-copy-steps), or [CreateRestoreImageTask](store-restore-how-it-works.md#CreateRestoreImageTask).
+ For AMIs created using [CreateImage](creating-an-ami-ebs.md#how-to-create-ebs-ami) (creates an AMI from an instance), the source AMI ID is the ID of the AMI used to launch the instance.
+ The source AMI information is not available for:
  + AMIs created using [RegisterImage](creating-an-ami-ebs.md#creating-launching-ami-from-snapshot) because they were created from snapshots.
  + For some older AMIs.
+ The source AMI information is preserved when:
  + AMIs are copied across Regions.
  + Source AMIs are deregistered (deleted).
  + You don’t have access to the source AMIs.
+ Each ancestry list is limited to 50 AMIs.

## View AMI ancestry


You can view an AMI's ancestry using the following methods.

------
#### [ Console ]

**To view the ancestry of an AMI**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **AMIs**.

1. Select an AMI and choose the **AMI ancestry** tab.

1. The **AMI ancestry entries** table lists all the AMIs in the ancestry list.
   + **AMI ID** – The identifier of each AMI in the ancestry list. The first entry in the table is the selected AMI, followed by its ancestors.
   + **Source AMI ID** – The ID of the AMI from which the AMI in the **AMI ID** column was created. A dash (**-**) indicates the end of the AMI ancestry list.
   + **Source AMI Region** – The AWS Region where the source AMI is located.
   + **Ancestry level** – The position in the ancestry list, where:
     + **0 (input AMI)** indicates the selected AMI whose ancestry you want to know.
     + Increasing numbers show older ancestors.
     + ***n* (original AMI)** indicates the root AMI, with the number indicating how far back the ancestry list goes.
   + **Creation date** – When the AMI was created, in UTC format.
   + **Owner alias** – The alias of the AMI owner (for example, `amazon`). A dash (**-**) indicates that the AMI has no owner alias.

------
#### [ AWS CLI ]

**To view the ancestry of an AMI**  
Use the [get-image-ancestry](https://docs.aws.amazon.com/cli/latest/reference/ec2/get-image-ancestry.html) command and specify the AMI ID.

```
aws ec2 get-image-ancestry \
    --image-id ami-1111111111EXAMPLE \
    --region us-east-1
```

The following is example output. The output lists AMIs in ancestry order: the first entry is the specified (input) AMI, followed by its parent, parent's parent, and so on, and ends with the root AMI.

```
{
    "ImageAncestryEntries": [
        {
            "CreationDate": "2025-01-17T18:37:50.000Z",
            "ImageId": "ami-1111111111EXAMPLE", // Input AMI
            "SourceImageId": "ami-2222222222EXAMPLE",
            "SourceImageRegion": "us-east-1"

        },
        {
            "CreationDate": "2025-01-17T18:37:50.000Z",
            "ImageId": "ami-2222222222EXAMPLE", // Parent AMI
            "SourceImageId": "ami-3333333333EXAMPLE",
            "SourceImageRegion": "us-east-1"
        },
        ...
        {
            "CreationDate": "2025-01-17T18:37:50.000Z",
            "ImageId": "ami-8888888888EXAMPLE", // Root AMI
            "ImageOwnerAlias": "aws-marketplace",
            "SourceImageId": "ami-9999999999EXAMPLE",
            "SourceImageRegion": "us-east-2"
        }
    ]
}
```

------
#### [ PowerShell ]

**To view the ancestry of an AMI**  
Use the [Get-EC2ImageAncestry](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2ImageAncestry.html) cmdlet.

```
Get-EC2ImageAncestry -ImageId ami-1111111111EXAMPLE
```

The following is example output. The output lists AMIs in ancestry order: the first entry is the specified (input) AMI, followed by its parent, parent's parent, and so on, and ends with the root AMI.

```
ImageAncestryEntries : {
    @{
        CreationDate = "2025-01-17T18:37:50.000Z"
        ImageId = "ami-1111111111EXAMPLE"    # Input AMI
        SourceImageId = "ami-2222222222EXAMPLE"
        SourceImageRegion = "us-east-1"
    },
    @{
        CreationDate = "2025-01-17T18:37:50.000Z"
        ImageId = "ami-2222222222EXAMPLE"    # Parent AMI
        SourceImageId = "ami-3333333333EXAMPLE"
        SourceImageRegion = "us-east-1"
    },
    ...
    @{
        CreationDate = "2025-01-17T18:37:50.000Z"
        ImageId = "ami-8888888888EXAMPLE"    # Root AMI
        ImageOwnerAlias = "aws-marketplace"
        SourceImageId = "ami-9999999999EXAMPLE"
        SourceImageRegion = "us-east-2"
    }
}
```

------

## Identify the source AMI


If you only need to identify the immediate parent (source) AMI used to create an AMI, you can use the following methods.

------
#### [ Console ]

**To identify the source AMI used to create the selected AMI**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **AMIs**.

1. Select the AMI to view its details.

   The source AMI information appears in the following fields: **Source AMI ID** and **Source AMI Region**

------
#### [ AWS CLI ]

**To identify the source AMI used to create the specified AMI**  
Use the [describe-images](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) command.

```
aws ec2 describe-images \
    --region us-east-1 \
    --image-ids ami-0abcdef1234567890 \
    --query "Images[].{ID:SourceImageId,Region:SourceImageRegion}"
```

The following is example output.

```
[
    {
        "ID": "ami-0abcdef1234567890",
        "Region": "us-west-2"
    }
}
```

------
#### [ PowerShell ]

**To identify the source AMI used to create the specified AMI**  
Use the [Get-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Image.html) cmdlet.

```
Get-EC2Image -ImageId ami-0abcdef1234567890 | Select SourceImageId, SourceImageRegion
```

The following is example output.

```
SourceImageId           SourceImageRegion
-------------           -----------------
ami-0abcdef1234567890 us-west-2
```

------

# Manage and monitor AMI usage
AMI usage

AWS provides several features to help you manage and monitor your AMI usage effectively. You can track which accounts are using your shared AMIs, identify when your AMIs were last used, and discover which resources in your AWS account are referencing specific AMIs.

The following table provides an overview of the features for managing and monitoring AMI usage:


| Feature | Use case | Key benefits | 
| --- | --- | --- | 
| [AMI usage reports](your-ec2-ami-usage.md) | Gain visibility into which AWS accounts are using your AMIs and how much each AMI is being used. |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-ami-usage.html)  | 
| [Last used tracking](ami-last-launched-time.md) | Check when your AMI was last used. |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-ami-usage.html)  | 
| [AMI reference check](ec2-ami-references.md) | Ensure your AWS resources are using the latest compliant AMIs. |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-ami-usage.html)  | 

**Topics**
+ [

# View your AMI usage
](your-ec2-ami-usage.md)
+ [

# Check when an Amazon EC2 AMI was last used
](ami-last-launched-time.md)
+ [

# Identify your resources referencing specified AMIs
](ec2-ami-references.md)

# View your AMI usage


If you share your Amazon Machine Images (AMIs) with other AWS accounts—whether with specific AWS accounts, organizations, organizational units (OUs), or publicly—you can see how these AMIs are used by creating AMI usage reports. The reports provide visibility into:
+ Which AWS accounts are using your AMIs in EC2 instances or launch templates
+ How many EC2 instances or launch templates are referencing each AMI

AMI usage reports help you manage your AMIs more effectively by helping you:
+ Identify the AWS accounts and resource types referencing your AMIs so that you can safely deregister or disable AMIs.
+ Identify unused AMIs for deregistration to reduce storage costs.
+ Identify your most used AMIs.

**Topics**
+ [

## How AMI usage reports work
](#how-ami-usage-reports-work)
+ [

## Create an AMI usage report
](#create-ami-usage-reports)
+ [

## View AMI usage reports
](#view-ami-usage-reports)
+ [

## Delete an AMI usage report
](#delete-ami-usage-reports)
+ [

## Report quotas
](#ami-usage-report-quotas)

## How AMI usage reports work


When you create an AMI usage report, you specify:
+ The AMI to report on.
+ The AWS accounts to check (specific accounts or all accounts).
+ The resource types to check (EC2 instances, launch templates, or both).
+ For launch templates, the number of versions to check (defaults to the 20 most recent versions).

Amazon EC2 creates a separate report for each AMI. Each report provides:
+ A list of the AWS accounts using the AMI.
+ A count of the resources referencing the AMI by resource type per account. Note that for launch templates, if an AMI is referenced in multiple versions of a launch template, the count is only 1.

**Important**  
When you generate an AMI usage report, it might not contain the most recent activity. Instance activity from the past 24 hours and launch template activity from the past few days might not appear in the report.

Amazon EC2 automatically deletes a report 30 days after creation. You can download reports from the EC2 console to retain locally.

## Create an AMI usage report


To view how your AMI is being used, you must first create an AMI usage report, specifying the accounts and resource types to report on. Once the report is created, you can view the contents of the report. You can also download the report from the EC2 console.

------
#### [ Console ]

**To create an AMI usage report**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **AMIs**.

1. Select an AMI and choose **Actions**, **AMI usage**, **View my AMI usage**.

1. On the **Create my AMI usage report** page, do the following:

   1. For **Resource types**, select one or more resource types to report on.

   1. For **Account IDs**, do one of the following:
      + Choose **Specify accounts IDs** and then choose **Add account ID** for each account to report on.
      + Choose **Include all accounts** to report on all accounts.

   1. Choose **Create my AMI usage report**.

1. On the AMI page, choose the **My AMI usage** tab.

1. Choose a report ID to view its details.

------
#### [ AWS CLI ]

**To create an AMI usage report for a list of accounts**  
Use the [create-image-usage-report](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-image-usage-report.html) command with the following required parameters:
+ `--image-id` – The ID of the AMI to report on.
+ `--resource-types` – The types of resources to check. In the following example, the resource types to check are EC2 instances and launch templates. In addition, the number of launch template versions to check is also specified (`version-depth=100`).

 To report on specific accounts, use the `--account-ids` parameter to specify the ID of each account to report on.

```
aws ec2 create-image-usage-report \
    --image-id ami-0abcdef1234567890 \
    --account-ids 111122223333 444455556666 123456789012 \
    --resource-types ResourceType=ec2:Instance \
      'ResourceType=ec2:LaunchTemplate,ResourceTypeOptions=[{OptionName=version-depth,OptionValues=100}]'
```

**To create an AMI usage report of all accounts**  
To report on all accounts using the specified AMI, use the same command but omit the `--account-ids` parameter.

```
aws ec2 create-image-usage-report \
    --image-id ami-0abcdef1234567890 \
    --resource-types ResourceType=ec2:Instance \
      'ResourceType=ec2:LaunchTemplate,ResourceTypeOptions=[{OptionName=version-depth,OptionValues=100}]'
```

The following is example output.

```
{
    "ReportId": "amiur-00b877d192f6b02d0"
}
```

**To monitor the report creation status**  
Use the [describe-image-usage-reports](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-image-usage-reports.html) command and specify the report ID.

```
aws ec2 describe-image-usage-reports --report-ids amiur-00b877d192f6b02d0
```

The following is example output. The initial value of the `State` field is `pending`. To be able to view the report entries, the state must be `available`.

```
{
    "ImageUsageReports": [
        {
            "ImageId": "ami-0e9ae3dc21c2b3a64",
            "ReportId": "amiur-abcae3dc21c2b3999",
            "ResourceTypes": [
                {"ResourceType": "ec2:Instance"}
            ],
            "State": "pending",
            "CreationTime": "2025-09-29T13:27:12.322000+00:00",
            "ExpirationTime": "2025-10-28T13:27:12.322000+00:00"
        }
    ]
}
```

------
#### [ PowerShell ]

**To create an AMI usage report for a list of accounts**  
Use the [New-EC2ImageUsageReport](https://docs.aws.amazon.com/powershell/latest/reference/items/New-EC2ImageUsageReport.html) cmdlet with the following required parameters:
+ `-ImageId` – The ID of the AMI to report on.
+ `-ResourceType` – The types of resources to check. In the following example, the resource types to check are EC2 instances and launch templates. In addition, the number of launch template versions to check is also specified (`'version-depth' = 100`).

 To report on specific accounts, use the `-AccountId` parameter to specify the ID of each account to report on.

```
New-EC2ImageUsageReport `
    -ImageId ami-0abcdef1234567890 `
    -AccountId 111122223333 444455556666 123456789012 `
    -ResourceType @(
        @{ResourceType = 'ec2:Instance'},
        @{ResourceType = 'ec2:LaunchTemplate'ResourceTypeOptions = @{'version-depth' = 100}
        })
```

**To create an AMI usage report of all accounts**  
To report on all accounts using the specified AMI, use the same command but omit the `-AccountId` parameter.

```
New-EC2ImageUsageReport `
    -ImageId ami-0abcdef1234567890 `
    -ResourceType @(
        @{ResourceType = 'ec2:Instance'},
        @{ResourceType = 'ec2:LaunchTemplate'ResourceTypeOptions = @{'version-depth' = 100}
        })
```

The following is example output.

```
ReportId
--------
amiur-00b877d192f6b02d0
```

**To monitor the report creation status**  
Use the [Get-EC2ImageUsageReport](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2ImageUsageReport.html) command and specify the report ID.

```
Get-EC2ImageUsageReport -ReportId amiur-00b877d192f6b02d0
```

The following is example output. The initial value of the `State` field is `pending`. To be able to view the report entries, the state must be `available`.

```
ImageUsageReports
-----------------
{@{ImageId=ami-0e9ae3dc21c2b3a64; ReportId=amiur-abcae3dc21c2b3999; ResourceTypes=System.Object[]; State=pending; CreationTime=2025-09-29; ExpirationTime=2025-10-28}}
```

------

## View AMI usage reports


You can view all the usage reports you've created for an AMI in the past 30 days. Amazon EC2 automatically deletes a report 30 days after creation.

For each report, you can see the AWS accounts that are using the AMI, and for each account, a count of the resources referencing the AMI by resource type. You can also see when the report creation was initiated. This information is only available when the report is in the **Complete** (console) or `available` (AWS CLI) state.

**Important**  
When you generate an AMI usage report, it might not contain the most recent activity. Instance activity from the past 24 hours and launch template activity from the past few days might not appear in the report.

------
#### [ Console ]

**To view an AMI usage report**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **AMIs**.

1. Select an AMI.

1. Choose the **My usage reports** tab.

   The report list shows:
   + All reports generated in the past 30 days for the selected AMI.
   + For each report, the **Report initiated time** column shows the date the report was created.

1. Choose the ID of a report to view its contents.

1. To go back to the **My usage reports** tab on the AMI details page, choose **View all reports for this AMI**.

------
#### [ AWS CLI ]

**To list all the AMI usage reports for the specified AMI**  
Use the [describe-image-usage-reports](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-image-usage-reports.html) command and specify the ID of the AMI to get a list of its reports.

```
aws ec2 describe-image-usage-reports --image-ids ami-0abcdef1234567890
```

The following is example output. Each report ID is listed along with the resource types that were scanned and the report creation and expiration dates. You can use this information to identify the reports whose entries you want to view.

```
{
  "ImageUsageReports": [
    {
      "ImageId": "ami-0abcdef1234567890",
      "ReportId": "amiur-1111111111111111",
      "ResourceTypes": [
        {
          "ResourceType": "ec2:Instance"
        }
      ],
      "State": "available",
      "CreationTime": "2025-09-29T13:27:12.322000+00:00",
      "ExpirationTime": "2025-10-28T13:27:12.322000+00:00",
      "Tags": []
    },
    {
      "ImageId": "ami-0abcdef1234567890",
      "ReportId": "amiur-22222222222222222",
      "ResourceTypes": [
        {
          "ResourceType": "ec2:Instance"
        },
        {
          "ResourceType": "ec2:LaunchTemplate"
        }
      ],
      "State": "available",
      "CreationTime": "2025-10-01T13:27:12.322000+00:00",
      "ExpirationTime": "2025-10-30T13:27:12.322000+00:00",
      "Tags": []
    }
  ],
  "NextToken": "opaque"
}
```

**To view the contents of an AMI usage report for the specified AMI**  
Use the [describe-image-usage-report-entries](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-image-usage-report-entries.html) command and specify the ID of the AMI. The response returns all the reports for the specified AMI, showing the accounts that have used the AMI and their resource counts.

```
aws ec2 describe-image-usage-report-entries --image-ids ami-0abcdef1234567890
```

The following is example output.

```
{
  "ImageUsageReportEntries": [
    {
      "ImageId": "ami-0abcdef1234567890",
      "ResourceType": "ec2:Instance",
      "AccountId": "123412341234",
      "UsageCount": 15,
      "ReportCreationTime": "2025-09-29T13:27:12.322000+00:00",
      "ReportId": "amiur-1111111111111111"
    },
    {
      "ImageId": "ami-0abcdef1234567890",
      "ResourceType": "ec2:Instance",
      "AccountId": "123412341234",
      "UsageCount": 2,
      "ReportCreationTime": "2025-10-01T13:27:12.322000+00:00",
      "ReportId": "amiur-22222222222222222"
    },
    {
      "ImageId": "ami-0abcdef1234567890",
      "ResourceType": "ec2:Instance",
      "AccountId": "001100110011",
      "UsageCount": 39,
      "ReportCreationTime": "2025-10-01T13:27:12.322000+00:00",
      "ReportId": "amiur-22222222222222222"
    }
  ],
  "NextToken": "opaque"
}
```

**To view the contents of an AMI usage report for the specified report**  
Use the [describe-image-usage-report-entries](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-image-usage-report-entries.html) command and specify the ID of the report. The response returns all the entries for the specified report, showing the accounts that have used the AMI and their resource counts.

```
aws ec2 describe-image-usage-report-entries --report-ids amiur-11111111111111111
```

The following is example output.

```
{
  "ImageUsageReportEntries": [
    {
      "ImageId": "ami-0abcdef1234567890",
      "ResourceType": "ec2:Instance",
      "AccountId": "123412341234",
      "UsageCount": 15,
      "ReportCreationTime": "2025-09-29T13:27:12.322000+00:00",
      "ReportId": "amiur-11111111111111111"
    },
    {
      "ImageId": "ami-0abcdef1234567890",
      "ResourceType": "ec2:LaunchTemplate",
      "AccountId": "123412341234",
      "UsageCount": 4,
      "ReportCreationTime": "2025-09-29T13:27:12.322000+00:00",
      "ReportId": "amiur-11111111111111111"
    },
    {
      "ImageId": "ami-0abcdef1234567890",
      "ResourceType": "ec2:LaunchTemplate",
      "AccountId": "001100110011",
      "UsageCount": 2,
      "ReportCreationTime": "2025-09-29T13:27:12.322000+00:00",
      "ReportId": "amiur-11111111111111111"
    }
  ],
  "NextToken": "opaque"
}
```

------
#### [ PowerShell ]

**To list all the AMI usage reports for the specified AMI**  
Use the [Get-EC2ImageUsageReport](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2ImageUsageReport.html) cmdlet and specify the ID of the AMI to get a list of its reports.

```
Get-EC2ImageUsageReport -ImageId ami-0abcdef1234567890
```

The following is example output. Each report ID is listed along with the resource types that were scanned and the report creation and expiration dates. You can use this information to identify the reports whose entries you want to view.

```
@{
    ImageUsageReports = @(
        @{
            ImageId = "ami-0abcdef1234567890"
            ReportId = "amiur-1111111111111111"
            ResourceTypes = @(
                @{
                    ResourceType = "ec2:Instance"
                }
            )
            State = "available"
            CreationTime = "2025-09-29T13:27:12.322000+00:00"
            ExpirationTime = "2025-10-28T13:27:12.322000+00:00"
        },
        @{
            ImageId = "ami-0abcdef1234567890"
            ReportId = "amiur-22222222222222222"
            ResourceTypes = @(
                @{
                    ResourceType = "ec2:Instance"
                }
            )
            State = "available"
            CreationTime = "2025-09-30T13:27:12.322000+00:00"
            ExpirationTime = "2025-10-29T13:27:12.322000+00:00"
        },
        @{
            ImageId = "ami-0abcdef1234567890"
            ReportId = "amiur-33333333333333333"
            ResourceTypes = @(
                @{
                    ResourceType = "ec2:Instance"
                }
            )
            State = "available"
            CreationTime = "2025-10-01T13:27:12.322000+00:00"
            ExpirationTime = "2025-10-30T13:27:12.322000+00:00"
        }
    )
    NextToken = "opaque"
}
```

**To view the contents of an AMI usage report for the specified AMI**  
Use the [Get-EC2ImageUsageReportEntry](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2ImageUsageReportEntry.html) cmdlet and specify the ID of the AMI. The response returns all the reports for the specified AMI, showing the accounts that have used the AMI and their resource counts.

```
Get-EC2ImageUsageReportEntry -ImageId ami-0abcdef1234567890
```

The following is example output.

```
ImageUsageReportEntries : {@{
    ImageId = "ami-0abcdef1234567890"
    ResourceType = "ec2:Instance"
    AccountId = "123412341234"
    UsageCount = 15
    ReportCreationTime = "2025-09-29T13:27:12.322000+00:00"
    ReportId = "amiur-1111111111111111"
    }, @{
    ImageId = "ami-0abcdef1234567890"
    ResourceType = "ec2:Instance"
    AccountId = "123412341234"
    UsageCount = 7
    ReportCreationTime = "2025-09-30T13:27:12.322000+00:00"
    ReportId = "amiur-22222222222222222"
    }...}
NextToken : opaque
```

**To view the contents of an AMI usage report for the specified report**  
Use the [Get-EC2ImageUsageReportEntry](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2ImageUsageReportEntry.html) cmdlet and specify the ID of the report. The response returns all the entries for the specified report, showing the accounts that have used the AMI and their resource counts.

```
Get-EC2ImageUsageReportEntry -ReportId amiur-11111111111111111
```

The following is example output.

```
ImageUsageReportEntries : {@{
    ImageId = "ami-0abcdef1234567890"
    ResourceType = "ec2:Instance"
    AccountId = "123412341234"
    UsageCount = 15
    ReportCreationTime = "2025-09-29T13:27:12.322000+00:00"
    ReportId = "amiur-11111111111111111"
    }, @{
    ImageId = "ami-0abcdef1234567890"
    ResourceType = "ec2:LaunchTemplate"
    AccountId = "123412341234"
    UsageCount = 4
    ReportCreationTime = "2025-09-29T13:27:12.322000+00:00"
    ReportId = "amiur-11111111111111111"
    }, @{
    ImageId = "ami-0abcdef1234567890"
    ResourceType = "ec2:LaunchTemplate"
    AccountId = "************"
    UsageCount = 2
    ReportCreationTime = "2025-09-29T13:27:12.322000+00:00"
    ReportId = "amiur-11111111111111111"
    }}
NextToken : opaque
```

------

## Delete an AMI usage report


Amazon EC2 automatically deletes a report 30 days after it was created. You can delete it manually before that time.

------
#### [ Console ]

**To delete an AMI usage report**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **AMIs**.

1. Select an AMI.

1. Choose the **My AMI usage** tab.

1. Choose the option button next to the report to delete, and then choose **Delete**.

------
#### [ AWS CLI ]

**To delete an AMI usage report**  
Use the [delete-image-usage-report](https://docs.aws.amazon.com/cli/latest/reference/ec2/delete-image-usage-report.html) command and specify the ID of the report.

```
aws ec2 delete-image-usage-report --report-id amiur-0123456789abcdefg
```

------
#### [ PowerShell ]

**To delete an AMI usage report**  
Use the [Remove-EC2ImageUsageReport](https://docs.aws.amazon.com/powershell/latest/reference/items/Remove-EC2ImageUsageReport.html) cmdlet and specify the ID of the report.

```
Remove-EC2ImageUsageReport -ReportId amiur-0123456789abcdefg
```

------

## Report quotas


The following quotas apply to creating AMI usage reports. The quotas apply per AWS Region.


| Description | Quota | 
| --- | --- | 
| In-progress (pending) AMI usage reports per AWS account | 2,000 | 
| In-progress (pending) AMI usage reports per AMI | 1 | 

# Check when an Amazon EC2 AMI was last used
Check when an AMI was last used

Amazon EC2 automatically tracks the date and time when an AMI was last used to launch an instance. If you have an AMI that has not been used to launch an instance in a long time, consider whether the AMI is a good candidate for [deregistration](deregister-ami.md) or [deprecation](ami-deprecate.md).

**Considerations**
+ When an AMI is used to launch an instance, there is a 24-hour delay before that usage is reported.
+ You must be the owner of the AMI to get the last launched time.
+ AMI usage data is available starting April 2017.

------
#### [ Console ]

**To view the last launched time of an AMI**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the left navigation pane, choose **AMIs**.

1. From the filter bar, choose **Owned by me**.

1. Select the checkbox for the AMI.

1. On the **Details** tab, find **Last launched time**.

------
#### [ AWS CLI ]

**To view the last launched time by describing the AMI**  
Use the [describe-images](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) command. If `LastLaunchedTime` is not present in the output, verify that you own the AMI.

```
aws ec2 describe-images \
    --image-id ami-0abcdef1234567890 \
    --query Images[].LastLaunchedTime \
    --output text
```

The following is example output.

```
2025-02-17T20:22:19Z
```

**To view the last launched time attribute of an AMI**  
Use the [describe-image-attribute](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-image-attribute.html) command. You must be the owner of the specified AMI.

```
aws ec2 describe-image-attribute \
    --image-id ami-0abcdef1234567890 \
    --attribute lastLaunchedTime \
    --query LastLaunchedTime.Value \
    --output text
```

The following is example output.

```
2025-02-17T20:22:19Z
```

------
#### [ PowerShell ]

**To view the last launched time by describing the AMI**  
Use the [Get-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Image.html) cmdlet. If `LastLaunchedTime` is not present in the output, verify that you own the AMI.

```
(Get-EC2Image -ImageId ami-0abcdef1234567890).LastLaunchedTime
```

The following is example output.

```
2025-02-17T20:22:19Z
```

**To view the last launched time attribute of an AMI**  
Use the [Get-EC2ImageAttribute](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2ImageAttribute.html) cmdlet. You must be the owner of the specified AMI.

```
(Get-EC2ImageAttribute `
    -ImageId ami-0abcdef1234567890 `
    -Attribute LastLaunchedTime).LastLaunchedTime
```

The following is example output.

```
2025-02-17T20:22:19Z
```

------

# Identify your resources referencing specified AMIs


You can identify your AWS resources that reference specified Amazon Machine Images (AMIs), regardless of whether the AMIs are public or private, or who owns them. This visibility helps you ensure your resources use the latest compliant AMIs.

**Key benefits**

Checking AMI references helps you:
+ Audit the use of AMIs in your account.
+ Check where specific AMIs are being referenced.
+ Maintain compliance by updating your resources to reference the latest AMIs.

 

**Topics**
+ [

## Supported resources
](#ec2-ami-references-supported-resources)
+ [

## How AMI reference checks work
](#how-ami-references-works)
+ [

## Required IAM permissions
](#ami-references-required-permissions)
+ [

## Steps for checking AMI references
](#ami-reference-procedures)

## Supported resources


AMI references can be checked in:
+ EC2 instances
+ Launch templates
+ SSM parameters
+ Image Builder image recipes
+ Image Builder container recipes

## How AMI reference checks work


**Basic operation**

When you run an AMI reference check, you:
+ Specify which AMIs to check.
+ Choose which resource types to scan.
+ Receive a list of your resources that reference the specified AMIs.

**Resource type selection**

In the console, you select the resource types to scan.

In the CLI, you specify resource types to scan using one or both of the following CLI parameters:
+ `IncludeAllResourceTypes`: Scans all supported resource types.
+ `ResourceTypes`: Scans your specified resource types.

**Response scoping**

You can scope the response for EC2 instances and launch templates by customizing the `ResourceTypeOptions` values using the `ResourceTypes` parameter. The console and `IncludeAllResourceTypes` parameter both use default option values. When `ResourceTypes` and `IncludeAllResourceTypes` are used together, the `ResourceTypes` option values take precedence over the defaults.

The following are the default values:


| Resource type | Scoping option (`OptionName`) | Purpose | Default values for `OptionValue` and console | 
| --- | --- | --- | --- | 
| EC2 instances | state-name | Filter by instance state | pending, running, shutting-down, terminated, stopping, stopped (all states) | 
| Launch templates | version-depth | Specify the number of launch template versions to check (starting from the most recent version) | 10 (most recent versions) | 

## Required IAM permissions


To use the DescribeImageReferences API to identify your resources that are referencing specified AMIs, you need the following IAM permissions to describe the resources:
+ `ec2:DescribeInstances`
+ `ec2:DescribeLaunchTemplates`
+ `ec2:DescribeLaunchTemplateVersions`
+ `ssm:DescribeParameters`
+ `ssm:GetParameters`
+ `imagebuilder:ListImageRecipes`
+ `imagebuilder:ListContainerRecipes`
+ `imagebuilder:GetContainerRecipe`

**Example IAM policy for using the DescribeImageReferences API**  
The following example policy grants you the permissions to use the DescribeImageReferences API, which includes the permissions to describe EC2 instances, launch templates, Systems Manager parameters, Image Builder image recipes, and Image Builder container recipes.

------
#### [ JSON ]

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": "ec2:DescribeImageReferences",
			"Resource": "*"
		},
		{
			"Effect": "Allow",
			"Action": [
				"ec2:DescribeInstances",
				"ec2:DescribeLaunchTemplates",
				"ec2:DescribeLaunchTemplateVersions",
				"ssm:DescribeParameters",
				"ssm:GetParameters",
				"imagebuilder:ListImageRecipes",
				"imagebuilder:ListContainerRecipes",
				"imagebuilder:GetContainerRecipe"
			],
			"Resource": "*",
			"Condition": {
				"ForAnyValue:StringEquals": {
					"aws:CalledVia": [
						"ec2-images.amazonaws.com"
					]
				}
			}
		}
	]
}
```

------

**Important**  
We strongly recommend using the AWS managed policy [https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonEC2ImageReferencesAccessPolicy.html](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonEC2ImageReferencesAccessPolicy.html) instead of creating the policy yourself. Creating a custom IAM policy that provides only the required permissions requires time and expertise, and will require updates as new resource types become available.  
The `AmazonEC2ImageReferencesAccessPolicy` managed policy:  
Grants all the permissions needed to use the DescribeImageReferences API (these include the permissions to describe EC2 instances, launch templates, Systems Manager parameters, and Image Builder container and image recipes).
Automatically supports new resource types as they become available (especially important when using the `IncludeAllResourceTypes` parameter).
You can attach the `AmazonEC2ImageReferencesAccessPolicy` policy to your IAM identities (users, groups, and roles).   
To view the permissions included in this policy, see [https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonEC2ImageReferencesAccessPolicy.html](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonEC2ImageReferencesAccessPolicy.html) in the *AWS Managed Policy Reference*.

## Steps for checking AMI references


Use the following procedures to identify which of your AWS resources are referencing specified AMIs.

------
#### [ Console ]

**To identify resources referencing specified AMIs**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **AMIs**.

1. Select one or more AMIs to check for references.

1. Choose **Actions**, **AMI usage**, **View referenced resources**.

1. On the **View resources referencing selected AMIs** page:

   1. For **Resource types**, select one or more resource types.

   1. Choose **View resources**.

1. The **Resources referencing selected AMIs** section appears. The list displays the resources referencing the specified AMIs. Each row provides the following information:
   + **AMI ID** – The ID of the referenced AMI.
   + **Resource type** – The resource type of the resource referencing the AMI.
   + **Resource ID** – The ID of the resource referencing the AMI.

------
#### [ AWS CLI ]

**To check AMI references for specific resource types**  
Use the [describe-image-references](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-image-references.html) command with the `--resource-types` parameter. The following example checks EC2 instances (scoping by instance state), launch templates (scoping to the 20 most recent launch template versions), and other specific resource types.

```
aws ec2 describe-image-references \
    --image-ids ami-0abcdef1234567890 ami-1234567890abcdef0 \
    --resource-types \
        'ResourceType=ec2:Instance,ResourceTypeOptions=[{OptionName=state-name,OptionValues=[running,pending]}]' \
        'ResourceType=ec2:LaunchTemplate,ResourceTypeOptions=[{OptionName=version-depth,OptionValues=[20]}]' \
        'ResourceType=ssm:Parameter' \
        'ResourceType=imagebuilder:ImageRecipe' \
        'ResourceType=imagebuilder:ContainerRecipe'
```

The following is example output.

```
{
    "ImageReferences": [
        {
            "ImageId": "ami-0abcdef1234567890",
            "ResourceType": "ec2:Instance",
            "Arn": "arn:aws:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0"
        },
        {
            "ImageId": "ami-1234567890abcdef0",
            "ResourceType": "ec2:LaunchTemplate",
            "Arn": "arn:aws:ec2:us-east-1:123456789012:launch-template/lt-1234567890abcdef0"
        }
    ]
}
```

**To check AMI references for all the supported resource types**  
Use the [describe-image-references](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-image-references.html) command with the `--include-all-resource-types` parameter.

```
aws ec2 describe-image-references \
    --image-ids ami-0abcdef1234567890 ami-1234567890abcdef0 \
    --include-all-resource-types
```

**To check AMI references for all supported resource types and specific options**  
Use the [describe-image-references](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-image-references.html) command with both the `--include-all-resource-types` and `--resource-types` parameters. This example checks all resource types while scoping the response for EC2 instances to running or pending instances.

```
aws ec2 describe-image-references \
    --image-ids ami-0abcdef1234567890 ami-1234567890abcdef0 \
    --include-all-resource-types \
    --resource-types 'ResourceType=ec2:Instance,ResourceTypeOptions=[{OptionName=state-name,OptionValues=[running,pending]}]'
```

------
#### [ PowerShell ]

**To check AMI references for specific resource types**  
Use the [Get-EC2ImageReference](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2ImageReference.html) cmdlet with the `-ResourceType` parameter. The following example checks EC2 instances (scoping by instance state), launch templates (scoping to the 20 most recent launch template versions), and other specific resource types.

```
Get-EC2ImageReference `
    -ImageId 'ami-0abcdef1234567890', 'ami-1234567890abcdef0' `
    -ResourceType @(
        @{
            ResourceType = 'ec2:Instance'
            ResourceTypeOptions = @(
                @{
                    OptionName = 'state-name'
                    OptionValues = @('running', 'pending')
                }
            )
        },
        @{
            ResourceType = 'ec2:LaunchTemplate'
            ResourceTypeOptions = @(
                @{
                    OptionName = 'version-depth'
                    OptionValues = @('20')
                }
            )
        },
        @{
            ResourceType = 'ssm:Parameter'
        },
        @{
            ResourceType = 'imagebuilder:ImageRecipe'
        },
        @{
            ResourceType = 'imagebuilder:ContainerRecipe'
        }
    )
```

**To check AMI references for all the supported resource types**  
Use the [Get-EC2ImageReference](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2ImageReference.html) cmdlet with the `-IncludeAllResourceTypes` parameter.

```
Get-EC2ImageReference `
    -ImageId 'ami-0abcdef1234567890', 'ami-1234567890abcdef0' `
    -IncludeAllResourceTypes
```

**To check AMI references for all supported resource types and specific options**  
Use the [Get-EC2ImageReference](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2ImageReference.html) cmdlet with both the `-IncludeAllResourceTypes` and `-ResourceType` parameters. This example checks all resource types while scoping the response for EC2 instances to running or pending instances.

```
Get-EC2ImageReference `
    -ImageId 'ami-0abcdef1234567890', 'ami-1234567890abcdef0' `
    -IncludeAllResourceTypes `
    -ResourceType @(
        @{
            ResourceType = 'ec2:Instance'
            ResourceTypeOptions = @(
                @{
                    OptionName = 'state-name'
                    OptionValues = @('running', 'pending')
                }
            )
        }
    )
```

------

# Deprecate an Amazon EC2 AMI
Deprecate an AMI

You can deprecate an AMI to indicate that it is out of date and should not be used. You can also specify a future deprecation date for an AMI, indicating when the AMI will be out of date. For example, you might deprecate an AMI that is no longer actively maintained, or you might deprecate an AMI that has been superseded by a newer version. By default, deprecated AMIs do not appear in AMI listings, preventing new users from using out-of-date AMIs. However, existing users and launch services, such as launch templates and Auto Scaling groups, can continue to use a deprecated AMI by specifying its ID. To delete the AMI so that users and services cannot use it, you must [deregister](deregister-ami.md) it.

After an AMI is deprecated:
+ For AMI users, the deprecated AMI does not appear in [DescribeImages](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeImages.html) API calls unless you specify its ID or specify that deprecated AMIs must appear. AMI owners continue to see deprecated AMIs in [DescribeImages](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeImages.html) API calls.
+ For AMI users, the deprecated AMI is not available to select via the EC2 console. For example, a deprecated AMI does not appear in the AMI catalog in the launch instance wizard. AMI owners continue to see deprecated AMIs in the EC2 console.
+ For AMI users, if you know the ID of a deprecated AMI, you can continue to launch instances using the deprecated AMI by using the API, CLI, or the SDKs.
+ Launch services, such as launch templates and Auto Scaling groups, can continue to reference deprecated AMIs.
+ EC2 instances that were launched using an AMI that is subsequently deprecated are not affected, and can be stopped, started, and rebooted.

You can deprecate both private and public AMIs.

**Topics**
+ [

## Costs
](#ami-deprecate-costs)
+ [

## Considerations
](#ami-deprecate-limitations)
+ [

## Deprecate an AMI
](#deprecate-ami)
+ [

## Describe deprecated AMIs
](#describe-deprecate-ami)
+ [

## Cancel AMI deprecation
](#cancel-deprecate-ami)

## Costs


When you deprecate an AMI, the AMI is not deleted. The AMI owner continues to pay for the AMI's snapshots. To stop paying for the snapshots, the AMI owner must delete the AMI by [deregistering](deregister-ami.md) it.

## Considerations

+ To deprecate an AMI, you must be the owner of the AMI.
+ AMIs that have not been used recently to launch an instance might be good candidates for deprecation or deregistering. For more information, see [Check when an Amazon EC2 AMI was last used](ami-last-launched-time.md).
+ You can create Amazon Data Lifecycle Manager EBS-backed AMI policies to automate the deprecation of EBS-backed AMIs. For more information, see [Create AMI lifecycle policies](https://docs.aws.amazon.com/ebs/latest/userguide/ami-policy.html).
+ By default, the deprecation date of all public AMIs is set to two years from the AMI creation date. You can set the deprecation date to earlier than two years. To cancel the deprecation date, or to move the deprecation to a later date, you must make the AMI private by only [sharing it with specific AWS accounts](sharingamis-explicit.md).

## Deprecate an AMI


You can deprecate an AMI on a specific date and time. You must be the owner of the AMI.

The upper limit for the deprecation date is 10 years from now, except for public AMIs, where the upper limit is 2 years from the creation date. You can't specify a date in the past.

------
#### [ Console ]

**To deprecate an AMI on a specific date**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the left navigator, choose **AMIs**.

1. From the filter bar, choose **Owned by me**.

1. Select the AMI, and then choose **Actions**, **Manage AMI Deprecation**. You can select multiple AMIs to set the same deprecation date of several AMIs at once.

1. Select the **Enable** checkbox, and then enter the deprecation date and time. 

1. Choose **Save**.

------
#### [ AWS CLI ]

**To deprecate an AMI on a specific date**  
Use the [enable-image-deprecation](https://docs.aws.amazon.com/cli/latest/reference/ec2/enable-image-deprecation.html) command. If you specify a value for seconds, Amazon EC2 rounds the seconds to the nearest minute.

```
aws ec2 enable-image-deprecation \
    --image-id ami-0abcdef1234567890 \
    --deprecate-at "2025-04-15T13:17:12.000Z"
```

------
#### [ PowerShell ]

**To deprecate an AMI on a specific date**  
Use the [Enable-EC2ImageDeprecation](https://docs.aws.amazon.com/powershell/latest/reference/items/Enable-EC2ImageDeprecation.html) cmdlet. If you specify a value for seconds, Amazon EC2 rounds the seconds to the nearest minute.

```
Enable-EC2ImageDeprecation `
    -ImageId ami-0abcdef1234567890 `
    -DeprecateAt 2025-04-15T13:17:12.000Z
```

------

## Describe deprecated AMIs


You can view the deprecation date and time of an AMI, and filter AMIs by deprecation date.

------
#### [ Console ]

**To view the deprecation date of an AMI**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the left navigator, choose **AMIs**, and then select the AMI.

1. Check the **Deprecation time** field (if you selected the checkbox next to the AMI, it's located on the **Details** tab). The field shows the deprecation date and time of the AMI. If the field is empty, the AMI is not deprecated.

**To filter AMIs by deprecation date**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the left navigator, choose **AMIs**.

1. From the filter bar, choose **Owned by me** or **Private images** (private images include AMIs that are shared with you as well as owned by you).

1. In the Search bar, enter **Deprecation time** (as you enter the letters, the **Deprecation time** filter appears), and then choose an operator and a date and time.

------
#### [ AWS CLI ]

When you describe all AMIs, the results depend on whether you are an AMI user or the AMI owner.
+ **AMI user** – By default, when you describe all AMIs, deprecated AMIs that are shared with you but not owned by you are excluded. To include deprecated AMIs in the results, specify the `--include-deprecated` option.
+ **AMI owner** – When you describe all AMIs, all AMIs that you own, including deprecated AMIs, are included. You can't exclude deprecated AMIs that you own by using the `--no-include-deprecated` option.

**To include deprecated AMIs when describing all AMIs for an account**  
Use the following [describe-images](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) command.

```
aws ec2 describe-images 
    --owners 123456789012 \   
    --include-deprecated
```

**To describe the deprecated AMIs for your account**  
Use the following [describe-images](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) command.

```
aws ec2 describe-images \
    --owners self \
    --query "Images[?DeprecationTime!=null].ImageId" \
    --output text
```

The following is example output.

```
ami-0abcdef1234567890
```

**To describe the deprecation date of an AMI**  
Use the following [describe-images](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) command. If `DeprecationTime` is not present in the output, the AMI is not deprecated or set to deprecate at a future date.

```
aws ec2 describe-images \
    --image-ids ami-0abcdef1234567890 \
    --query Images[].DeprecationTime \
    --output text
```

The following is example output.

```
2025-05-01T00:00:00.000Z
```

------
#### [ PowerShell ]

**To list the deprecated AMIs for your account**  
Use the [Get-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Image.html) cmdlet.

```
(Get-EC2Image -Owner self | Where-Object {$_.DeprecationTime -ne $null}).ImageId
```

The following is example output.

```
ami-0abcdef1234567890
```

**To describe the deprecation date of an AMI**  
Use the [Get-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Image.html) cmdlet. If `DeprecationTime` is not present in the output, the AMI is not deprecated or set to deprecate at a future date.

```
(Get-EC2Image -ImageId ami-0abcdef1234567890).DeprecationTime
```

The following is example output.

```
2025-05-01T00:00:00.000Z
```

------

## Cancel AMI deprecation


You can cancel the deprecation of an AMI, which removes the deprecation date and time. You must be the AMI owner to perform this procedure.

------
#### [ Console ]

**To cancel the deprecation of an AMI**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the left navigator, choose **AMIs**.

1. From the filter bar, choose **Owned by me**.

1. Select the AMI, and then choose **Actions**, **Manage AMI Deprecation**. You can select multiple AMIs to cancel the deprecation of several AMIs at once.

1. Clear the **Enable** checkbox, and then choose **Save**.

------
#### [ AWS CLI ]

**To cancel the deprecation of an AMI**  
Use the following [disable-image-deprecation](https://docs.aws.amazon.com/cli/latest/reference/ec2/disable-image-deprecation.html) command.

```
aws ec2 disable-image-deprecation --image-id ami-0abcdef1234567890
```

------
#### [ PowerShell ]

**To cancel the deprecation of an AMI**  
Use the [Disable-EC2ImageDeprecation](https://docs.aws.amazon.com/powershell/latest/reference/items/Disable-EC2ImageDeprecation.html) cmdlet.

```
Disable-EC2ImageDeprecation -ImageId ami-0abcdef1234567890
```

------

# Disable an Amazon EC2 AMI
Disable an AMI

You can disable an AMI to prevent it from being used for instance launches. You can't launch new instances from a disabled AMI. You can re-enable a disabled AMI so that it can be used again for instance launches.

You can disable both private and public AMIs.

To reduce storage costs for disabled EBS-backed AMIs that are rarely used, but which need to be retained long term, you can archive their associated snapshots. For more information, see [Archive Amazon EBS snapshots](https://docs.aws.amazon.com/ebs/latest/userguide/snapshot-archive.html) in the *Amazon EBS User Guide*.

**Topics**
+ [

## How AMI disable works
](#how-disable-ami-works)
+ [

## Costs
](#ami-disable-costs)
+ [

## Prerequisites
](#ami-disable-prerequisites)
+ [

## Required IAM permissions
](#ami-disable-iam-permissions)
+ [

## Disable an AMI
](#disable-ami)
+ [

## Describe disabled AMIs
](#describe-disabled-ami)
+ [

## Re-enable a disabled AMI
](#re-enable-a-disabled-ami)

## How AMI disable works


**Warning**  
Disabling an AMI removes all its launch permissions.

**When an AMI is disabled:**
+ The AMI's state changes to `disabled`.
+ A disabled AMI can't be shared. If an AMI was public or previously shared, it is made private. If an AMI was shared with an AWS account, organization, or Organizational Unit, they lose access to the disabled AMI. 
+ A disabled AMI does not appear in [https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeImages.html](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeImages.html) API calls by default.
+ A disabled AMI does not appear under the **Owned by me** console filter. To find disabled AMIs, use the **Disabled images** console filter.
+ A disabled AMI is not available to select for instance launches in the EC2 console. For example, a disabled AMI does not appear in the AMI catalog in the launch instance wizard or when creating a launch template.
+ Launch services, such as launch templates and Auto Scaling groups, can continue to reference disabled AMIs. Subsequent instance launches from a disabled AMI will fail, so we recommend updating launch templates and Auto Scaling groups to reference available AMIs only.
+ EC2 instances that were previously launched using an AMI that is subsequently disabled are not affected, and can be stopped, started, and rebooted.
+ You can't delete snapshots associated with disabled AMIs. Attempting to delete an associated snapshot results in the `snapshot is currently in use` error.

**When an AMI is re-enabled:**
+ The AMI's state changes to `available`, and it can be used to launch instances.
+ The AMI can be shared.
+ AWS accounts, organizations, and Organizational Units that lost access to the AMI when it was disabled do not regain access automatically, but the AMI can be shared with them again.

## Costs


When you disable an AMI, the AMI is not deleted. If the AMI is an EBS-backed AMI, you continue to pay for the AMI's EBS snapshots. If you want to keep the AMI, you might be able to reduce your storage costs by archiving the snapshots. For more information, see [Archive Amazon EBS snapshots](https://docs.aws.amazon.com/ebs/latest/userguide/snapshot-archive.html) in the *Amazon EBS User Guide*. If you don't want to keep the AMI and its snapshots, you must deregister the AMI and delete the snapshots. For more information, see [Deregister an AMI](deregister-ami.md).

## Prerequisites


To disable or re-enable an AMI, you must be the owner of the AMI.

## Required IAM permissions


To disable and re-enable an AMI, you must have the following IAM permissions:
+ `ec2:DisableImage`
+ `ec2:EnableImage`

## Disable an AMI


You can disable an AMI by using the EC2 console or the AWS Command Line Interface (AWS CLI). You must be the AMI owner to perform this procedure.

------
#### [ Console ]

**To disable an AMI**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the left navigation pane, choose **AMIs**.

1. From the filter bar, choose **Owned by me**.

1. Select the AMI, and then choose **Actions**, **Disable AMI**. You can select multiple AMIs to disable at once.

1. In the **Disable AMI** window, choose **Disable AMI**.

------
#### [ AWS CLI ]

**To disable an AMI**  
Use the following [https://docs.aws.amazon.com/cli/latest/reference/ec2/disable-image.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/disable-image.html) command.

```
aws ec2 disable-image --image-id ami-0abcdef1234567890
```

------
#### [ PowerShell ]

**To disable an AMI**  
Use the [Disable-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Disable-EC2Image.html) cmdlet.

```
Disable-EC2Image -ImageId ami-0abcdef1234567890
```

------

## Describe disabled AMIs


You can view disabled AMIs in the EC2 console and by using the AWS CLI.

You must be the AMI owner to view disabled AMIs. Because disabled AMIs are made private, you can't view disabled AMIs if you're not the owner.

------
#### [ Console ]

**To view disabled AMIs**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the left navigation pane, choose **AMIs**.

1. From the filter bar, choose **Disabled images**.  
![\[The Disabled images filter.\]](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/images/ami-filter-by-disabled-images.png)

------
#### [ AWS CLI ]

By default, when you describe all AMIs, the disabled AMIs are not included in the results. To include disabled AMIs in the results, specify the `--include-disabled` option. The `State` field for an AMI is `disabled` if the AMI is disabled.

**To include disabled AMIs when describing all AMIs for an account**  
Use the following [https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) command.

```
aws ec2 describe-images \
    --owners 123456789012 \
    --include-disabled
```

**To list the disabled AMIs for your account**  
Use the following [https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) command.

```
aws ec2 describe-images \
    --owners self \
    --include-disabled \
    --filters Name=state,Values=disabled \
    --query Images[].ImageId \
    --output text
```

The following is example output.

```
ami-0abcdef1234567890
```

**To describe the status of an AMI**  
Use the following [https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) command. If `DeprecationTime` is not present in the output, the AMI is not deprecated or set to deprecate at a future date.

```
aws ec2 describe-images \
    --image-ids ami-0abcdef1234567890 \
    --query Images[].State \
    --output text
```

The following is example output.

```
disabled
```

------
#### [ PowerShell ]

By default, when you describe all AMIs, the disabled AMIs are not included in the results. To include disabled AMIs in the results, specify the `-IncludeDisabled` parameter. The `State` field for an AMI is `disabled` if the AMI is disabled.

**To list the disabled AMIs for your account**  
Use the [Get-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Image.html) cmdlet.

```
(Get-EC2Image `
    -Owner self `
    -IncludeDisabled $true | Where-Object {$_.State -eq "disabled"}).ImageId
```

The following is example output.

```
ami-0abcdef1234567890
```

**To describe the status of an AMI**  
Use the [Get-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Image.html) cmdlet.

```
(Get-EC2Image -ImageId ami-0abcdef1234567890).State.Value
```

The following is example output.

```
disabled
```

------

## Re-enable a disabled AMI


You can re-enable a disabled AMI. You must be the AMI owner to perform this procedure.

------
#### [ Console ]

**To re-enable a disabled AMI**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the left navigation pane, choose **AMIs**.

1. From the filter bar, choose **Disabled images**.

1. Select the AMI, and then choose **Actions**, **Enable AMI**. You can select multiple AMIs to re-enable several AMIs at once.

1. In the **Enable AMI** window, choose **Enable**.

------
#### [ AWS CLI ]

**To re-enable a disabled AMI**  
Use the following [https://docs.aws.amazon.com/cli/latest/reference/ec2/enable-image.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/enable-image.html) command.

```
aws ec2 enable-image --image-id ami-0abcdef1234567890
```

------
#### [ PowerShell ]

**To re-enable a disabled AMI**  
Use the [Enable-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Enable-EC2Image.html) cmdlet.

```
Enable-EC2Image -ImageId ami-0abcdef1234567890
```

------

# Deregister an Amazon EC2 AMI
Deregister an AMI

When you deregister an AMI, Amazon EC2 permanently deletes it. After you deregister an AMI, you can't use it to launch new instances. You might consider deregistering an AMI when you have finished using it.

To protect against accidental or malicious deregistering of an AMI, you can turn on [deregistration protection](ami-deregistration-protection.md). If you accidentally deregister an EBS-backed AMI, you can use the [Recycle Bin](https://docs.aws.amazon.com/ebs/latest/userguide/recycle-bin.html) to restore it only if you restore it within the allowed time period before it is permanently deleted.

When deregistering an AMI, you can optionally delete its associated snapshots at the same time. However, if a snapshot is associated with multiple AMIs, it won't be deleted even if specified for deletion, although the AMI will still be deregistered. Any snapshots not deleted will continue to incur storage costs.

Deregistering an AMI has no effect on any instances that were launched from the AMI. You can continue to use these instances. By default, deregistering an AMI also has no effect on any snapshots that were created during the AMI creation process. You'll continue to incur usage costs for these instances and storage costs for the snapshots. Therefore, to avoid incurring unnecessary costs, we recommend that you terminate any instances and delete any snapshots that you do not need. You can delete the snapshots either automatically during deregistration or manually after deregistration. For more information, see [Avoid costs from unused resources](#delete-unneeded-resources-to-avoid-unnecessary-costs).

For instances launched from an AMI that is subsequently deregistered, you can still view some high-level information about the AMI by using the `describe-instance-image-metadata` AWS CLI command. For more information, see [describe-instance-image-metadata](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instance-image-metadata.html).

**Topics**
+ [

## Considerations
](#deregister-ami-considerations)
+ [

## Deregister an AMI
](#deregister-an-ami)
+ [

## Avoid costs from unused resources
](#delete-unneeded-resources-to-avoid-unnecessary-costs)
+ [

# Protect an Amazon EC2 AMI from deregistration
](ami-deregistration-protection.md)

## Considerations

+ You can't deregister an AMI that is not owned by your account.
+ You can't use Amazon EC2 to deregister an AMI that is managed by the AWS Backup service. Instead, use AWS Backup to delete the corresponding recovery points in the backup vault. For more information, see [Deleting backups](https://docs.aws.amazon.com/aws-backup/latest/devguide/deleting-backups.html) in the *AWS Backup Developer Guide*.

## Deregister an AMI


You can deregister EBS-backed AMIs and Amazon S3-backed AMIs. For EBS-backed AMIs, you can optionally delete the associated snapshots at the same time. However, if a snapshot is associated with other AMIs, it will not be deleted even if specified for deletion.

------
#### [ Console ]

**To deregister an AMI**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **AMIs**.

1. From the filter bar, choose **Owned by me** to list your available AMIs, or choose **Disabled images** to list your disabled AMIs.

1. Select the AMI to deregister.

1. Choose **Actions**, **Deregister AMI**.

1. (Optional) To delete the associated snapshots during deregistration, select the **Delete associated snapshots** checkbox.
**Note**  
If a snapshot is associated with other AMIs, it is not deleted, even if the checkbox is selected.

1. Choose **Deregister AMI**.

   It might take a few minutes before the console removes the AMI from the list. Choose **Refresh** to refresh the status.

------
#### [ AWS CLI ]

**To deregister an AMI**  
Use the following [deregister-image](https://docs.aws.amazon.com/cli/latest/reference/ec2/deregister-image.html) command.

```
aws ec2 deregister-image --image-id ami-0abcdef1234567890
```

**To deregister an AMI and delete its associated snapshots**  
Use the following [deregister-image](https://docs.aws.amazon.com/cli/latest/reference/ec2/deregister-image.html) command and specify the `--delete-associated-snapshots` parameter. Note that if a snapshot is associated with other AMIs, it is not deleted, even if you specify this parameter.

```
aws ec2 deregister-image \
    --image-id ami-0abcdef1234567890 \
    --delete-associated-snapshots
```

------
#### [ PowerShell ]

**To deregister an AMI**  
Use the [Unregister-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Unregister-EC2Image.html) cmdlet.

```
Unregister-EC2Image -ImageId ami-0abcdef1234567890
```

**To deregister an AMI and delete its associated snapshots**  
Use the [Unregister-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Unregister-EC2Image.html) cmdlet and specify the `-DeleteAssociatedSnapshots` parameter. Note that if a snapshot is associated with other AMIs, it is not deleted, even if you specify this parameter.

```
Unregister-EC2Image `
    -ImageId ami-0abcdef1234567890 `
    -DeleteAssociatedSnapshots
```

------

## Avoid costs from unused resources


Deregistering an AMI doesn't, by default, delete all of the resources that are associated with the AMI. These resources include the snapshots for EBS-backed AMIs and the files in Amazon S3 for Amazon S3-backed AMIs. When you deregister an AMI, you also don't terminate or stop any instances launched from the AMI.

You will continue to incur costs for storing the snapshots and files, and you will incur costs for any running instances.

To avoid incurring these types of unnecessary costs, we recommend deleting any resources that you don't need.

**EBS-backed AMIs**
+ Delete the associated snapshots while deregistering the AMI. For more information, see [Deregister an AMI](#deregister-an-ami).
+ If you deregister an AMI without deleting its associated snaphots, you can manually [delete the snapshots](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-deleting-snapshot.html#ebs-delete-snapshot). The snapshot of the instance root volume created during AMI creation has the following description format:

  ```
  Created by CreateImage(i-1234567890abcdef0) for ami-0abcdef1234567890
  ```
+ If you no longer need the instances that were launched from the AMI, you can [stop](Stop_Start.md#starting-stopping-instances) or [terminate](terminating-instances.md#terminating-instances-console) them. To list the instances, filter by the ID of the AMI.

**Amazon S3-backed AMIs**
+ Delete the bundle in Amazon S3 by using the [ec2-delete-bundle](ami-tools-commands.md#ami-delete-bundle) (AMI tools) command.
+ If the Amazon S3 bucket is empty after you delete the bundle, and you have no further use for that bucket, you can [delete the bucket](https://docs.aws.amazon.com/AmazonS3/latest/userguide/delete-bucket.html).
+ If you no longer need the instances that were launched from the AMI, you can [terminate](terminating-instances.md#terminating-instances-console) them. To list the instances, filter by the ID of the AMI.

# Protect an Amazon EC2 AMI from deregistration
Protect an AMI from deregistration

You can turn on *deregistration protection* on an AMI to prevent accidental or malicious deletion. When you turn on deregistration protection, the AMI can’t be deregistered by any user, regardless of their IAM permissions. If you want to deregister the AMI, you must first turn off the deregistration protection on it.

When you turn on deregistration protection on an AMI, you have the option to include a 24-hour cooldown period. This cooldown period is the time during which deregistration protection remains in effect after you turn it off. During this cooldown period, the AMI can’t be deregistered. When the cooldown period ends, the AMI can be deregistered.

Deregistration protection is turned off by default on all existing and new AMIs.

## Turn on deregistration protection


Use the following procedures to turn on deregistration protection.

------
#### [ Console ]

**To turn on deregistration protection**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **AMIs**.

1. From the filter bar, choose **Owned by me** to list your available AMIs, or choose **Disabled images** to list your disabled AMIs.

1. Select the AMI on which you want to turn on deregistration protection, and then choose **Actions**, **Manage AMI deregistration protection**.

1. In the **Manage AMI deregistration protection** dialog box, you can turn on deregistration protection with or without a cooldown period. Choose one of the following options:
   + **Enable with a 24-hour cooldown period** – With a cooldown period, the AMI can’t be deregistered for 24 hours when deregistration protection is turned off.
   + **Enable without cooldown** – Without a cooldown period, the AMI can be deregistered immediately when deregistration protection is turned off.

1. Choose **Save**.

------
#### [ AWS CLI ]

**To turn on deregistration protection**  
Use the [enable-image-deregistration-protection](https://docs.aws.amazon.com/cli/latest/reference/ec2/enable-image-deregistration-protection.html) command. To enable the optional cooldown period, include the `--with-cooldown` option.

```
aws ec2 enable-image-deregistration-protection \
    --image-id ami-0abcdef1234567890 \
    --with-cooldown
```

------
#### [ PowerShell ]

**To turn on deregistration protection**  
Use the [Enable-EC2ImageDeregistrationProtection](https://docs.aws.amazon.com/powershell/latest/reference/items/Enable-EC2ImageDeregistrationProtection.html) cmdlet. To enable the optional cooldown period, set the `-WithCooldown` parameter to `true`.

```
Enable-EC2ImageDeregistrationProtection `
    -ImageId ami-0abcdef1234567890 `
    -WithCooldown $true
```

------

## Turn off deregistration protection


Use the following procedures to turn off deregistration protection.

If you chose to include a 24-hour cooldown period when you turned on deregistration protection for the AMI, then, when you turn off deregistration protection, you won’t immediately be able to deregister the AMI. The cooldown period is the 24-hour time period during which deregistration protection remains in effect even after you turn it off. During this cooldown period, the AMI can’t be deregistered. After the cooldown period ends, the AMI can be deregistered.

------
#### [ Console ]

**To turn off deregistration protection**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **AMIs**.

1. From the filter bar, choose **Owned by me** to list your available AMIs, or choose **Disabled images** to list your disabled AMIs.

1. Select the AMI to turn off deregistration protection, and then choose **Actions**, **Manage AMI deregistration protection**.

1. In the **Manage AMI deregistration protection** dialog box, choose **Disable**.

1. Choose **Save**.

------
#### [ AWS CLI ]

**To turn off deregistration protection**  
Use the [disable-image-deregistration-protection](https://docs.aws.amazon.com/cli/latest/reference/ec2/disable-image-deregistration-protection.html) command.

```
aws ec2 disable-image-deregistration-protection --image-id ami-0abcdef1234567890
```

------
#### [ PowerShell ]

**To turn off deregistration protection**  
Use the [Disable-EC2ImageDeregistrationProtection](https://docs.aws.amazon.com/powershell/latest/reference/items/Disable-EC2ImageDeregistrationProtection.html) cmdlet.

```
Disable-EC2ImageDeregistrationProtection -ImageId ami-0abcdef1234567890
```

------

# Instance launch behavior with Amazon EC2 boot modes
Boot modes

When a computer boots, the first software that it runs is responsible for initializing the platform and providing an interface for the operating system to perform platform-specific operations.

In Amazon EC2, two variants of the boot mode software are supported: Unified Extensible Firmware Interface (UEFI) and Legacy BIOS.

**Possible boot mode parameters on an AMI**  
An AMI can have one of the following boot mode parameter values: `uefi`, `legacy-bios`, or `uefi-preferred`. The AMI boot mode parameter is optional. For AMIs with no boot mode parameter, the instances launched from these AMIs use the default boot mode value of the instance type.

**Purpose of the AMI boot mode parameter**  
The AMI boot mode parameter signals to Amazon EC2 which boot mode to use when launching an instance. When the boot mode parameter is set to `uefi`, EC2 attempts to launch the instance on UEFI. If the operating system is not configured to support UEFI, the instance launch will be unsuccessful.

**UEFI Preferred boot mode parameter**  
You can create AMIs that support both UEFI and Legacy BIOS by using the `uefi-preferred` boot mode parameter. When the boot mode parameter is set to `uefi-preferred`, and if the instance type supports UEFI, the instance is launched on UEFI. If the instance type does not support UEFI, the instance is launched on Legacy BIOS.

**Warning**  
Some features, like UEFI Secure Boot, are only available on instances that boot on UEFI. When you use the `uefi-preferred` AMI boot mode parameter with an instance type that does not support UEFI, the instance will launch as Legacy BIOS and the UEFI-dependent feature will be disabled. If you rely on the availability of a UEFI-dependent feature, set your AMI boot mode parameter to `uefi`.

**Default boot modes for instance types**
+ Graviton instance types: UEFI
+ Intel and AMD instance types: Legacy BIOS

**Zone support**  
UEFI boot is not supported in Wavelength Zones.

**Topics**
+ [

# Requirements to launch an EC2 instance in UEFI boot mode
](launch-instance-boot-mode.md)
+ [

# Determine the boot mode parameter of an Amazon EC2 AMI
](ami-boot-mode.md)
+ [

# Determine the supported boot modes of an EC2 instance type
](instance-type-boot-mode.md)
+ [

# Determine the boot mode of an EC2 instance
](instance-boot-mode.md)
+ [

# Determine the boot mode of the operating system for your EC2 instance
](os-boot-mode.md)
+ [

# Set the boot mode of an Amazon EC2 AMI
](set-ami-boot-mode.md)
+ [

# UEFI variables for Amazon EC2 instances
](uefi-variables.md)
+ [

# UEFI Secure Boot for Amazon EC2 instances
](uefi-secure-boot.md)

# Requirements to launch an EC2 instance in UEFI boot mode
Requirements for UEFI boot mode

The boot mode of an instance is determined by the configuration of the AMI, the operating system contained in it, and the instance type. To launch an instance in UEFI boot mode, you must meet the following requirements.

**AMI**  
The AMI must be configured for UEFI as follows:  
+ **Operating system** – The operating system contained in the AMI must be configured to use UEFI; otherwise, the instance launch will fail. For more information, see [Determine the boot mode of the operating system for your EC2 instance](os-boot-mode.md).
+ **AMI boot mode parameter** – The boot mode parameter of the AMI must be set to `uefi` or `uefi-preferred`. For more information, see [Determine the boot mode parameter of an Amazon EC2 AMI](ami-boot-mode.md).
**Linux** – The following Linux AMIs support UEFI:  
+ Amazon Linux 2023
+ Amazon Linux 2 (Graviton instance types only)
For other Linux AMIs, you must [configure the AMI](set-ami-boot-mode.md), import the AMI through [VM Import/Export](https://docs.aws.amazon.com/vm-import/latest/userguide/), or import the AMI through [CloudEndure](https://docs.cloudendure.com/).  
**Windows** – The following Windows AMIs support UEFI:  
+ Windows\$1Server-2025-\$1 (except for AMIs with the `BIOS-` name prefix)
+ TPM-Windows\$1Server-2022-English-Full-Base
+ TPM-Windows\$1Server-2022-English-Core-Base
+ TPM-Windows\$1Server-2019-English-Full-Base
+ TPM-Windows\$1Server-2019-English-Core-Base
+ TPM-Windows\$1Server-2016-English-Full-Base
+ TPM-Windows\$1Server-2016-English-Core-Base

**Instance type**  
All instances built on the AWS Nitro System support both UEFI and Legacy BIOS, except the following: bare metal instances, DL1, G4ad, P4, u-3tb1, u-6tb1, u-9tb1, u-12tb1, u-18tb1, u-24tb1, and VT1. For more information, see [Determine the supported boot modes of an EC2 instance type](instance-type-boot-mode.md).

The following table shows that the boot mode of an instance (indicated by the **Resulting instance boot mode** column) is determined by a combination of the boot mode parameter of the AMI (column 1), the boot mode configuration of the operating system contained in the AMI (column 2), and the boot mode support of the instance type (column 3).


| AMI boot mode parameter | Operating system boot mode configuration | Instance type boot mode support | Resulting instance boot mode | 
| --- | --- | --- | --- | 
| UEFI | UEFI | UEFI | UEFI | 
| Legacy BIOS | Legacy BIOS | Legacy BIOS | Legacy BIOS | 
| UEFI Preferred | UEFI | UEFI | UEFI | 
| UEFI Preferred | UEFI | UEFI and Legacy BIOS | UEFI | 
| UEFI Preferred | Legacy BIOS | Legacy BIOS | Legacy BIOS | 
| UEFI Preferred | Legacy BIOS | UEFI and Legacy BIOS | Legacy BIOS | 
| No boot mode specified - ARM | UEFI | UEFI | UEFI | 
| No boot mode specified - x86 | Legacy BIOS | UEFI and Legacy BIOS | Legacy BIOS | 

# Determine the boot mode parameter of an Amazon EC2 AMI
AMI boot mode parameter

The AMI boot mode parameter is optional. An AMI can have one of the following boot mode parameter values: `uefi`, `legacy-bios`, or `uefi-preferred`.

Some AMIs don't have a boot mode parameter. When an AMI has no boot mode parameter, the instances launched from the AMI use the default value of the instance type, which is `uefi` on Graviton, and `legacy-bios` on Intel and AMD instance types.

------
#### [ Console ]

**To determine the boot mode parameter of an AMI**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **AMIs**, and then select the AMI.

1. Inspect the **Boot mode** field.
   + A value of **uefi** indicates that the AMI supports UEFI.
   + A value of **uefi-preferred** indicates that the AMI supports both UEFI and Legacy BIOS.
   + If there is no value, the instances launched from the AMI use the default value of the instance type.

**To determine the boot mode parameter of an AMI when launching an instance**  
When launching an instance using the launch instance wizard, at the step to select an AMI, inspect the **Boot mode** field. For more information, see [Application and OS Images (Amazon Machine Image)](ec2-instance-launch-parameters.md#liw-ami).

------
#### [ AWS CLI ]

**To determine the boot mode parameter of an AMI**  
Use the [https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) command to determine the boot mode of an AMI.

```
aws ec2 describe-images \
    --region us-east-1 \
    --image-id ami-0abcdef1234567890 \
    --query Images[].BootMode \
    --output text
```

The following is example output.

```
uefi
```

In the output, a value of `uefi` indicates that the AMI supports UEFI. A value of `uefi-preferred` indicates that the AMI supports both UEFI and Legacy BIOS. If there is no value, the instances launched from the AMI use the default value of the instance type.

------
#### [ PowerShell ]

**To determine the boot mode parameter of an AMI**  
Use the [https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Image.html](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Image.html) cmdlet to determine the boot mode of an AMI.

```
Get-EC2Image -Region us-east-1 `
    -ImageId ami-0abcdef1234567890 | Format-List Name, BootMode, TpmSupport
```

The following is example output.

```
Name       : TPM-Windows_Server-2016-English-Full-Base-2023.05.10
BootMode   : uefi
TpmSupport : v2.0
```

In the output, the value of `BootMode` indicates the boot mode of the AMI. A value of `uefi` indicates that the AMI supports UEFI. A value of `uefi-preferred` indicates that the AMI supports both UEFI and Legacy BIOS. If there is no value, the instances launched from the AMI use the default value of the instance type.

------

# Determine the supported boot modes of an EC2 instance type
Instance type boot mode

You can determine the supported boot modes of an instance type.

The Amazon EC2 console does not display the supported boot modes of an instance type.

------
#### [ AWS CLI ]

Use the [https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instance-types.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instance-types.html) command to determine the supported boot modes of an instance type. The `--query` parameter filters the output to return only the supported boot modes.

The following example shows that the specified instance type supports both UEFI and Legacy BIOS boot modes.

```
aws ec2 describe-instance-types \
    --instance-types m5.2xlarge \
    --query "InstanceTypes[*].SupportedBootModes"
```

The following is example output.

```
[
    [
        "legacy-bios",
        "uefi"
    ]
]
```

The following example shows that `t2.xlarge` supports only Legacy BIOS.

```
aws ec2 describe-instance-types \
    --instance-types t2.xlarge \
    --query "InstanceTypes[*].SupportedBootModes"
```

The following is example output.

```
[
    [
        "legacy-bios"
    ]
]
```

------
#### [ PowerShell ]

Use the [https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2InstanceType.html](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2InstanceType.html) cmdlet to determine the supported boot modes of an instance type.

The following example shows that `m5.2xlarge` supports both UEFI and Legacy BIOS boot modes.

```
Get-EC2InstanceType -InstanceType m5.2xlarge | Format-List InstanceType, SupportedBootModes
```

The following is example output.

```
InstanceType       : m5.2xlarge
SupportedBootModes : {legacy-bios, uefi}
```

The following example shows that `t2.xlarge` supports only Legacy BIOS.

```
Get-EC2InstanceType -InstanceType t2.xlarge | Format-List InstanceType, SupportedBootModes
```

The following is example output.

```
InstanceType       : t2.xlarge
SupportedBootModes : {legacy-bios}
```

------

**To determine the instance types that support UEFI**  
You can determine the instance types that support UEFI. The Amazon EC2 console does not display the UEFI support of an instance type.

------
#### [ AWS CLI ]

The available instance types vary by AWS Region. To see the available instance types that support UEFI in a Region, use the [describe-instance-types](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instance-types.html) command. Include the `--filters` parameter to scope the results to the instance types that support UEFI and the `--query` parameter to scope the output to the value of `InstanceType`.

```
aws ec2 describe-instance-types \
    --filters Name=supported-boot-mode,Values=uefi \
    --query "InstanceTypes[*].[InstanceType]" --output text | sort
```

------
#### [ PowerShell ]

The available instance types vary by AWS Region. To see the available instance types that support UEFI in a Region, use the [Get-EC2InstanceType](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2InstanceType.html) cmdlet.

```
Get-EC2InstanceType | `
	Where-Object {$_.SupportedBootModes -Contains "uefi"} | `
	Sort-Object InstanceType | `
	Format-Table InstanceType -GroupBy CurrentGeneration
```

------

**To determine the instance types that support UEFI Secure Boot and persist non-volatile variables**  
Bare metal instances do not support UEFI Secure Boot and non-volatile variables, so these examples exclude them from the output. For information about UEFI Secure Boot, see [UEFI Secure Boot for Amazon EC2 instances](uefi-secure-boot.md).

------
#### [ AWS CLI ]

Use the [describe-instance-types](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instance-types.html) command, and exclude the bare metal instances from the output.

```
aws ec2 describe-instance-types \
    --filters Name=supported-boot-mode,Values=uefi Name=bare-metal,Values=false \
    --query "InstanceTypes[*].[InstanceType]" \
    --output text | sort
```

------
#### [ PowerShell ]

Use the [Get-EC2InstanceType](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2InstanceType.html) cmdlet, and exclude the bare metal instances from the output.

```
Get-EC2InstanceType | `
    Where-Object { `
        $_.SupportedBootModes -Contains "uefi" -and `
        $_.BareMetal -eq $False
        } | `
    Sort-Object InstanceType  | `
    Format-Table InstanceType, SupportedBootModes, BareMetal, `
        @{Name="SupportedArchitectures"; Expression={$_.ProcessorInfo.SupportedArchitectures}}
```

------

# Determine the boot mode of an EC2 instance
Instance boot mode

The boot mode of an instance is displayed in the **Boot mode** field in the Amazon EC2 console, and by the `currentInstanceBootMode` parameter in the AWS CLI.

When an instance is launched, the value for its boot mode parameter is determined by the value of the boot mode parameter of the AMI used to launch it, as follows:
+ An AMI with a boot mode parameter of `uefi` creates an instance with a `currentInstanceBootMode` parameter of `uefi`.
+ An AMI with a boot mode parameter of `legacy-bios` creates an instance with a `currentInstanceBootMode` parameter of` legacy-bios`.
+ An AMI with a boot mode parameter of `uefi-preferred` creates an instance with a `currentInstanceBootMode` parameter of `uefi` if the instance type supports UEFI; otherwise, it creates an instance with a `currentInstanceBootMode` parameter of `legacy-bios`.
+ An AMI with no boot mode parameter value creates an instance with a `currentInstanceBootMode` parameter value that is dependent on whether the AMI architecture is ARM or x86 and the supported boot mode of the instance type. The default boot mode is `uefi` on Graviton instance types, and `legacy-bios` on Intel and AMD instance types.

------
#### [ Console ]

**To determine the boot mode of an instance**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **Instances**, and then select your instance.

1. On the **Details** tab, inspect the **Boot mode** field.

------
#### [ AWS CLI ]

**To determine the boot mode of an instance**  
Use the [https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html) command to determine the boot mode of an instance. You can also determine the boot mode of the AMI that was used to the create the instance. 

```
aws ec2 describe-instances \
    --region us-east-1 \
    --instance-ids i-1234567890abcdef0 \
    --query Reservations[].Instances[].BootMode \
    --output text
```

The following is example output.

```
uefi
```

------
#### [ PowerShell ]

**To determine the boot mode of an instance**  
Use the [https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Instance.html](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Instance.html) cmdlet to determine the boot mode of an instance. You can also determine the boot mode of the AMI that was used to the create the instance. 

```
(Get-EC2Instance `
    -InstanceId i-1234567890abcdef0).Instances | Format-List BootMode, CurrentInstanceBootMode, InstanceType, ImageId
```

The following is example output.

```
BootMode                : uefi
CurrentInstanceBootMode : uefi
InstanceType            : c5a.large
ImageId                 : ami-0abcdef1234567890
```

------

# Determine the boot mode of the operating system for your EC2 instance
Operating system boot mode

The boot mode of the AMI guides Amazon EC2 on which boot mode to use to boot an instance. To view whether the operating system of your instance is configured for UEFI, you need to connect to your instance using SSH (Linux instances) or RDP (Windows instances).

Use the instructions for your instance's operating system.

## Linux


**To determine the boot mode of the instance’s operating system**

1. [Connect to your Linux instance using SSH](connect-linux-inst-ssh.md).

1. To view the boot mode of the operating system, try one of the following:
   + Run the following command.

     ```
     [ec2-user ~]$ sudo /usr/sbin/efibootmgr
     ```

     Expected output from an instance booted in UEFI boot mode

     ```
     BootCurrent: 0001
     Timeout: 0 seconds
     BootOrder: 0000,0001
     Boot0000* UiApp
     Boot0001* UEFI Amazon Elastic Block Store vol-xyz
     ```
   + Run the following command to verify the existence of the `/sys/firmware/efi` directory. This directory exists only if the instance boots using UEFI. If this directory doesn't exist, the command returns `Legacy BIOS Boot Detected`.

     ```
     [ec2-user ~]$ [ -d /sys/firmware/efi ] && echo "UEFI Boot Detected" || echo "Legacy BIOS Boot Detected"
     ```

     Expected output from an instance booted in UEFI boot mode

     ```
     UEFI Boot Detected
     ```

     Expected output from an instance booted in Legacy BIOS boot mode

     ```
     Legacy BIOS Boot Detected
     ```
   + Run the following command to verify that EFI appears in the `dmesg` output.

     ```
     [ec2-user ~]$ dmesg | grep -i "EFI"
     ```

     Expected output from an instance booted in UEFI boot mode

     ```
     [    0.000000] efi: Getting EFI parameters from FDT:
     [    0.000000] efi: EFI v2.70 by EDK II
     ```

## Windows


**To determine the boot mode of the instance’s operating system**

1. [Connect to your Windows instance using RDP](connecting_to_windows_instance.md).

1. Go to **System Information** and check the **BIOS Mode** row.  
![\[System Information window showing the BIOS Mode row selected. The value for BIOS Mode is Legacy.\]](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/images/BIOS-mode-win.png)

# Set the boot mode of an Amazon EC2 AMI
Set AMI boot mode

By default, an AMI inherits the boot mode of the EC2 instance used to create the AMI. For example, if you create an AMI from an EC2 instance running on Legacy BIOS, the boot mode of the new AMI is `legacy-bios`. If you create an AMI from an EC2 instance with a boot mode of `uefi-preferred`, the boot mode of the new AMI is `uefi-preferred`.

When you register an AMI, you can set the boot mode of the AMI to `uefi`, `legacy-bios`, or `uefi-preferred`.

When the AMI boot mode is set to `uefi-preferred`, the instance boots as follows: 
+ For instance types that support both UEFI and Legacy BIOS (for example, `m5.large`), the instance boots using UEFI.
+ For instance types that support only Legacy BIOS (for example, `m4.large`), the instance boots using Legacy BIOS.

If you set the AMI boot mode to `uefi-preferred`, the operating system must support the ability to boot both UEFI and Legacy BIOS.

To convert an existing Legacy BIOS-based instance to UEFI, or an existing UEFI-based instance to Legacy BIOS, you must first modify the instance's volume and operating system to support the selected boot mode. Then, create a snapshot of the volume. Finally, create an AMI from the snapshot.

**Considerations**
+ Setting the AMI boot mode parameter does not automatically configure the operating system for the specified boot mode. You must first make suitable modifications to the instance's volume and operating system to support booting using the selected boot mode. Otherwise, the resulting AMI is not usable. For example, if you are converting a Legacy BIOS-based Windows instance to UEFI, you can use the [MBR2GPT](https://learn.microsoft.com/en-us/windows/deployment/mbr-to-gpt) tool from Microsoft to convert the system disk from MBR to GPT. The modifications that are required are operating system-specific. For more information, see the manual for your operating system.
+ You can't use the [https://docs.aws.amazon.com/cli/latest/reference/ec2/register-image.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/register-image.html) command or the [https://docs.aws.amazon.com/powershell/latest/reference/items/Register-EC2Image.html](https://docs.aws.amazon.com/powershell/latest/reference/items/Register-EC2Image.html) cmdlet to create an AMI that supports both [NitroTPM](nitrotpm.md) and UEFI Preferred.
+ Some features, like UEFI Secure Boot, are only available on instances that boot on UEFI. When you use the `uefi-preferred` AMI boot mode parameter with an instance type that does not support UEFI, the instance launches as Legacy BIOS and the UEFI-dependent feature is disabled. If you rely on the availability of a UEFI-dependent feature, set your AMI boot mode parameter to `uefi`.

------
#### [ AWS CLI ]

**To set the boot mode of an AMI**

1. Make suitable modifications to the instance's volume and operating system to support booting via the selected boot mode. The modifications that are required are operating system-specific. For more information, see the manual for your operating system.
**Warning**  
If you don't perform this step, the AMI will not be usable.

1. To find the volume ID of the instance, use the [https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html) command. You'll create a snapshot of this volume in the next step.

   ```
   aws ec2 describe-instances \
       --instance-ids i-1234567890abcdef0 \
       --query Reservations[].Instances[].BlockDeviceMappings
   ```

   The following is example output.

   ```
   [
       [
           {
               "DeviceName": "/dev/xvda",
               "Ebs": {
                   "AttachTime": "2024-07-11T01:05:51+00:00",
                   "DeleteOnTermination": true,
                   "Status": "attached",
                   "VolumeId": "vol-1234567890abcdef0"
               }
           }
       ]
   ]
   ```

1. To create a snapshot of the volume, use the [https://docs.aws.amazon.com/cli/latest/reference/ec2/create-snapshot.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-snapshot.html) command. Use the volume ID from the previous step.

   ```
   aws ec2 create-snapshot \
       --volume-id vol-01234567890abcdef \
       --description "my snapshot"
   ```

   The following is example output.

   ```
   {
       "Description": "my snapshot",
       "Encrypted": false,
       "OwnerId": "123456789012",
       "Progress": "",
       "SnapshotId": "snap-0abcdef1234567890",
       "StartTime": "",
       "State": "pending",
       "VolumeId": "vol-01234567890abcdef",
       "VolumeSize": 30,
       "Tags": []
   }
   ```

1. Wait until the state of the snapshot is `completed` before you go to the next step. To get the state of the snapshot, use the [https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-snapshots.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-snapshots.html) command with the snapshot ID from the previous step.

   ```
   aws ec2 describe-snapshots \
       --snapshot-ids snap-0abcdef1234567890 \
       --query Snapshots[].State \
       --output text
   ```

   The following is example output.

   ```
   completed
   ```

1. To create a new AMI, use the [https://docs.aws.amazon.com/cli/latest/reference/ec2/register-image.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/register-image.html) command. Use the value of `SnapshotId` from the output of **CreateSnapshot**.
   + To set the boot mode to UEFI, add the `--boot-mode` parameter with a value of `uefi`.

     ```
     aws ec2 register-image \
        --description "my image" \
        --name "my-image" \
        --block-device-mappings "DeviceName=/dev/sda1,Ebs={SnapshotId=snap-0abcdef1234567890,DeleteOnTermination=true}" \
        --root-device-name /dev/sda1 \
        --virtualization-type hvm \
        --ena-support \
        --boot-mode uefi
     ```
   + To set the boot mode to `uefi-preferred`, set the value of `--boot-mode` to `uefi-preferred`

     ```
     aws ec2 register-image \
        --description "my description" \
        --name "my-image" \
        --block-device-mappings "DeviceName=/dev/sda1,Ebs={SnapshotId=snap-0abcdef1234567890,DeleteOnTermination=true}" \
        --root-device-name /dev/sda1 \
        --virtualization-type hvm \
        --ena-support \
        --boot-mode uefi-preferred
     ```

1. (Optional) To verify that the newly-created AMI has the boot mode that you specified, use the [https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) command.

   ```
   aws ec2 describe-images \
       --image-id ami-1234567890abcdef0 \
       --query Images[].BootMode \
       --output text
   ```

   The following is example output.

   ```
   uefi
   ```

------
#### [ PowerShell ]

**To set the boot mode of an AMI**

1. Make suitable modifications to the instance's volume and operating system to support booting via the selected boot mode. The modifications that are required are operating system-specific. For more information, see the manual for your operating system.
**Warning**  
If you don't perform this step, the AMI will not be usable.

1. To find the volume ID of the instance, use the [https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Instance.html](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Instance.html) cmdlet.

   ```
   (Get-EC2Instance `
       -InstanceId i-1234567890abcdef0).Instances.BlockDeviceMappings.Ebs
   ```

   The following is example output.

   ```
   AssociatedResource  : 
   AttachTime          : 7/11/2024 1:05:51 AM
   DeleteOnTermination : True
   Operator            : 
   Status              : attached
   VolumeId            : vol-01234567890abcdef
   ```

1. To create a snapshot of the volume, use the [https://docs.aws.amazon.com/powershell/latest/reference/items/New-EC2Snapshot.html](https://docs.aws.amazon.com/powershell/latest/reference/items/New-EC2Snapshot.html) cmdlet. Use the volume ID from the previous step.

   ```
   New-EC2Snapshot `
       -VolumeId vol-01234567890abcdef `
       -Description "my snapshot"
   ```

   The following is example output.

   ```
   AvailabilityZone          : 
   Description               : my snapshot
   Encrypted                 : False
   FullSnapshotSizeInBytes   : 0
   KmsKeyId                  : 
   OwnerId                   : 123456789012
   RestoreExpiryTime         : 
   SnapshotId                : snap-0abcdef1234567890
   SseType                   : 
   StartTime                 : 4/25/2025 6:08:59 PM
   State                     : pending
   StateMessage              : 
   VolumeId                  : vol-01234567890abcdef
   VolumeSize                : 30
   ```

1. Wait until the state of the snapshot is `completed` before you go to the next step. To get the state of the snapshot, use the [https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Snapshot.html](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Snapshot.html) cmdlet with the snapshot ID from the previous step.

   ```
   (Get-EC2Snapshot `
       -SnapshotId snap-0abcdef1234567890).State.Value
   ```

   The following is example output.

   ```
   completed
   ```

1. To create a new AMI, use the [https://docs.aws.amazon.com/powershell/latest/reference/items/Register-EC2Image.html](https://docs.aws.amazon.com/powershell/latest/reference/items/Register-EC2Image.html) cmdlet. Use the value of `SnapshotId` from the output of **New-EC2Snapshot**.
   + To set the boot mode to UEFI, add the `-BootMode` parameter with a value of `uefi`.

     ```
     $block = @{SnapshotId=snap-0abcdef1234567890}
     Register-EC2Image ` 
        -Description "my image" `
        -Name "my-image" `
        -BlockDeviceMapping @{DeviceName="/dev/xvda";Ebs=$block} `
        -RootDeviceName /dev/xvda `
        -EnaSupport $true `
        -BootMode uefi
     ```
   + To set the boot mode to `uefi-preferred`, set the value of `-BootMode` to `uefi-preferred`

     ```
     $block = @{SnapshotId=snap-0abcdef1234567890}
     Register-EC2Image ` 
        -Description "my image" `
        -Name "my-image" `
        -BlockDeviceMapping @{DeviceName="/dev/xvda";Ebs=$block} `
        -RootDeviceName /dev/xvda `
        -EnaSupport $true `
        -BootMode uefi-preferred
     ```

1. (Optional) To verify that the newly-created AMI has the boot mode that you specified, use the [https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Image.html](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Image.html) cmdlet.

   ```
   (Get-EC2Image `
       -ImageId ami-1234567890abcdef0).BootMode.Value
   ```

   The following is example output.

   ```
   uefi
   ```

------

# UEFI variables for Amazon EC2 instances
UEFI variables

When you launch an instance where the boot mode is set to UEFI, a key-value store for variables is created. The store can be used by UEFI and the instance operating system for storing UEFI variables.

UEFI variables are used by the boot loader and the operating system to configure early system startup. They allow the operating system to manage certain settings of the boot process, like the boot order, or managing the keys for UEFI Secure Boot.

**Warning**  
Anyone who can connect to the instance (and potentially any software running on the instance), or anyone with permissions to use the [ GetInstanceUefiData](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_GetInstanceUefiData.html) API on the instance can read the variables. You should never store sensitive data, such as passwords or personally identifiable information, in the UEFI variable store.

**UEFI variable persistence**
+ For instances that were launched on or before May 10, 2022, UEFI variables are wiped on reboot or stop.
+ For instances that are launched on or after May 11, 2022, UEFI variables that are marked as non-volatile are persisted on reboot and stop/start.
+ Bare metal instances don't preserve UEFI non-volatile variables across instance stop/start operations.

# UEFI Secure Boot for Amazon EC2 instances
UEFI Secure Boot

UEFI Secure Boot builds on the long-standing secure boot process of Amazon EC2, and provides additional defense-in-depth that helps customers secure software from threats that persist across reboots. It ensures that the instance only boots software that is signed with cryptographic keys. The keys are stored in the key database of the [UEFI non-volatile variable store](uefi-variables.md). UEFI Secure Boot prevents unauthorized modification of the instance boot flow.

**Topics**
+ [

# How UEFI Secure Boot works with Amazon EC2 instances
](how-uefi-secure-boot-works.md)
+ [

# Requirements for UEFI Secure Boot on Amazon EC2
](launch-instance-with-uefi-sb.md)
+ [

# Verify whether an Amazon EC2 instance is enabled for UEFI Secure Boot
](verify-uefi-secure-boot.md)
+ [

# Create a Linux AMI with custom UEFI Secure Boot keys
](create-ami-with-uefi-secure-boot.md)
+ [

# Create the AWS binary blob for UEFI Secure Boot
](aws-binary-blob-creation.md)

# How UEFI Secure Boot works with Amazon EC2 instances
How UEFI Secure Boot works

UEFI Secure Boot is a feature specified in UEFI, which provides verification about the state of the boot chain. It is designed to ensure that only cryptographically verified UEFI binaries are executed after the self-initialization of the firmware. These binaries include UEFI drivers and the main bootloader, as well as chain-loaded components.

UEFI Secure Boot specifies four key databases, which are used in a chain of trust. The databases are stored in the UEFI variable store.

The chain of trust is as follows:

**Platform key (PK) database**  
The PK database is the root of trust. It contains a single public PK key that is used in the chain of trust for updating the key exchange key (KEK) database.  
To change the PK database, you must have the private PK key to sign an update request. This includes deleting the PK database by writing an empty PK key.

**Key exchange key (KEK) database**  
The KEK database is a list of public KEK keys that are used in the chain of trust for updating the signature (db) and denylist (dbx) databases.  
To change the public KEK database, you must have the private PK key to sign an update request.

**Signature (db) database**  
The db database is a list of public keys and hashes that are used in the chain of trust to validate all UEFI boot binaries.  
To change the db database, you must have the private PK key or any of the private KEK keys to sign an update request.

**Signature denylist (dbx) database**  
The dbx database is a list of public keys and binary hashes that are not trusted, and are used in the chain of trust as a revocation file.  
The dbx database always takes precedence over all other key databases.  
To change the dbx database, you must have the private PK key or any of the private KEK keys to sign an update request.  
The UEFI Forum maintains a publicly available dbx for many known-bad binaries and certs at [https://uefi.org/revocationlistfile](https://uefi.org/revocationlistfile).

**Important**  
UEFI Secure Boot enforces signature validation on any UEFI binaries. To permit execution of a UEFI binary in UEFI Secure Boot, you sign it with any of the private db keys described above.

By default, UEFI Secure Boot is disabled and the system is in `SetupMode`. When the system is in `SetupMode`, all key variables can be updated without a cryptographic signature. When the PK is set, UEFI Secure Boot is enabled and the SetupMode is exited.

# Requirements for UEFI Secure Boot on Amazon EC2
Requirements for UEFI Secure Boot

When you [launch an Amazon EC2 instance](LaunchingAndUsingInstances.md) with a supported AMI and a supported instance type, that instance will automatically validate UEFI boot binaries against its UEFI Secure Boot database. No additional configuration is required. You can also configure UEFI Secure Boot on an instance after launch.

**Note**  
UEFI Secure Boot protects your instance and its operating system against boot flow modifications. If you create a new AMI from a source AMI that has UEFI Secure Boot enabled and modify certain parameters during the copy process, such as changing the `UefiData` within the AMI, you can disable UEFI Secure Boot.

**Topics**
+ [

## Supported AMIs
](#uefi-amis)
+ [

## Supported instance types
](#uefi-instance)

## Supported AMIs


**Linux AMIs**  
To launch a Linux instance, the Linux AMI must have UEFI Secure Boot enabled.

Amazon Linux supports UEFI Secure Boot starting with AL2023 release 2023.1. However, UEFI Secure Boot isn't enabled in the default AMIs. For more information, see [UEFI Secure Boot](https://docs.aws.amazon.com/linux/al2023/ug/uefi-secure-boot.html) in the *AL2023 User Guide*. Older versions of Amazon Linux AMIs aren't enabled for UEFI Secure Boot. To use a supported AMI, you must perform a number of configuration steps on your own Linux AMI. For more information, see [Create a Linux AMI with custom UEFI Secure Boot keys](create-ami-with-uefi-secure-boot.md).

**Windows AMIs**  
To launch a Windows instance, the Windows AMI must have UEFI Secure Boot enabled. To find an AWS Windows AMI that's preconfigured for UEFI Secure Boot with Microsoft keys, see [Find Windows Server AMIs configured with NitroTPM and UEFI Secure Boot](https://docs.aws.amazon.com/ec2/latest/windows-ami-reference/ami-windows-tpm.html#ami-windows-tpm-find) in the *AWS Windows AMIs Reference*.

Currently, we do not support importing Windows with UEFI Secure Boot by using the [import-image](https://docs.aws.amazon.com/cli/latest/reference/ec2/import-image.html) command.

## Supported instance types


All virtualized instance types that support UEFI also support UEFI Secure Boot. For the instance types that support UEFI Secure Boot, see [Requirements for UEFI boot mode](launch-instance-boot-mode.md).

**Note**  
Bare metal instance types do not support UEFI Secure Boot.

# Verify whether an Amazon EC2 instance is enabled for UEFI Secure Boot
Verify if an instance is enabled for UEFI Secure Boot

You can use the following procedures to determine whether an Amazon EC2 is enabled for UEFI Secure Boot.

## Linux instances


You can use the `mokutil` utility to verify whether a Linux instance is enabled for UEFI Secure Boot. If `mokutil` is not installed on your instance, you must install it. For the installation instructions for Amazon Linux 2, see [Find and install software packages on an Amazon Linux 2 instance](https://docs.aws.amazon.com/linux/al2/ug/find-install-software.html). For other Linux distributions, see their specific documentation.

**To verify whether a Linux instance is enabled for UEFI Secure Boot**  
Connect to your instance and run the following command as `root` in a terminal window.

```
mokutil --sb-state 
```

The following is example output.
+ If UEFI Secure Boot is enabled, the output contains `SecureBoot enabled`.
+ If UEFI Secure Boot is not enabled, the output contains `SecureBoot disabled` or `Failed to read SecureBoot`.

## Windows instances


**To verify whether a Windows instance is enabled for UEFI Secure Boot**

1. Connect to your instance.

1. Open the msinfo32 tool.

1. Check the **Secure Boot State** field. If UEFI Secure Boot is enabled, the value is **Supported**, as shown in the following image.  
![\[Secure Boot State within System Information.\]](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/images/secure-boot-state-win.png)

You can also use the Windows PowerShell Cmdlet `Confirm-SecureBootUEFI` to check the Secure Boot status. For more information about the cmdlet, see [Confirm-SecureBootUEFI](https://learn.microsoft.com/en-us/powershell/module/secureboot/confirm-securebootuefi) in the Microsoft Documentation.

# Create a Linux AMI with custom UEFI Secure Boot keys
Create a Linux AMI with custom keys

These instructions show you how to create a Linux AMI with UEFI Secure Boot and custom-made private keys. Amazon Linux supports UEFI Secure Boot starting with AL2023 release 2023.1. For more information, see [UEFI Secure Boot on AL2023](https://docs.aws.amazon.com/linux/al2023/ug/uefi-secure-boot.html) in the *Amazon Linux 2023 User Guide*.

**Important**  
The following procedure is intended for **advanced users only**. You must have sufficient knowledge of SSL and Linux distribution boot flow to use these procedures.

**Prerequisites**
+ The following tools will be used:
  + OpenSSL – [https://www.openssl.org/](https://www.openssl.org/)
  + efivar – [https://github.com/rhboot/efivar](https://github.com/rhboot/efivar)
  + efitools – [https://git.kernel.org/pub/scm/linux/kernel/git/jejb/efitools.git/](https://git.kernel.org/pub/scm/linux/kernel/git/jejb/efitools.git/)
  + [get-instance-uefi-data](https://docs.aws.amazon.com/cli/latest/reference/ec2/get-instance-uefi-data.html) command
+ Your Linux instance must have been launched with a Linux AMI that supports UEFI boot mode, and have non-volatile data present.

Newly created instances without UEFI Secure Boot keys are created in `SetupMode`, which allows you to enroll your own keys. Some AMIs come preconfigured with UEFI Secure Boot and you cannot change the existing keys. If you want to change the keys, you must create a new AMI based on the original AMI.

You have two ways to propagate the keys in the variable store, which are described in Option A and Option B that follow. Option A describes how to do this from within the instance, mimicking the flow of real hardware. Option B describes how to create a binary blob, which is then passed as a base64-encoded file when you create the AMI. For both options, you must first create the three key pairs, which are used for the chain of trust.

**Topics**
+ [

## Task 1: Create key pairs
](#uefi-secure-boot-create-three-key-pairs)
+ [

## Task 2 - Option A: Add keys to the variable store from within the instance
](#uefi-secure-boot-optionA)
+ [

## Task 2 - Option B: Create a binary blob containing a pre-filled variable store
](#uefi-secure-boot-optionB)

## Task 1: Create key pairs


UEFI Secure Boot is based on the following three key databases, which are used in a chain of trust: the platform key (PK), the key exchange key (KEK), and the signature database (db).¹

You create each key on the instance. To prepare the public keys in a format that is valid for the UEFI Secure Boot standard, you create a certificate for each key. `DER` defines the SSL format (binary encoding of a format). You then convert each certificate into a UEFI signature list, which is the binary format that is understood by UEFI Secure Boot. And finally, you sign each certificate with the relevant key.

**Topics**
+ [

### Prepare to create the key pairs
](#uefisb-prepare-to-create-key-pairs)
+ [

### Key pair 1: Create the platform key (PK)
](#uefisb-create-key-pair-1)
+ [

### Key pair 2: Create the key exchange key (KEK)
](#uefisb-create-key-pair-2)
+ [

### Key pair 3: Create the signature database (db)
](#uefisb-create-key-pair-3)
+ [

### Sign the boot image (kernel) with the private key
](#uefi-secure-boot-sign-kernel)

### Prepare to create the key pairs


Before creating the key pairs, create a globally unique identifier (GUID) to be used in key generation.

1. [Connect to the instance](connect.md).

1. Run the following command in a shell prompt.

   ```
   uuidgen --random > GUID.txt
   ```

### Key pair 1: Create the platform key (PK)


The PK is the root of trust for UEFI Secure Boot instances. The private PK is used to update the KEK, which in turn can be used to add authorized keys to the signature database (db).

The X.509 standard is used for creating the key pair. For information about the standard, see [X.509](https://en.wikipedia.org/wiki/X.509) on *Wikipedia*.

**To create the PK**

1. Create the key. You must name the variable `PK`.

   ```
   openssl req -newkey rsa:4096 -nodes -keyout PK.key -new -x509 -sha256 -days 3650 -subj "/CN=Platform key/" -out PK.crt
   ```

   The following parameters are specified:
   + `-keyout PK.key` – The private key file.
   + `-days 3650` – The number of days that the certificate is valid.
   + `-out PK.crt` – The certificate that is used to create the UEFI variable.
   + `CN=Platform key` – The common name (CN) for the key. You can enter the name of your own organization instead of *Platform key*.

1. Create the certificate.

   ```
   openssl x509 -outform DER -in PK.crt -out PK.cer
   ```

1. Convert the certificate into a UEFI signature list.

   ```
   cert-to-efi-sig-list -g "$(< GUID.txt)" PK.crt PK.esl
   ```

1. Sign the UEFI signature list with the private PK (self-signed).

   ```
   sign-efi-sig-list -g "$(< GUID.txt)" -k PK.key -c PK.crt PK PK.esl PK.auth
   ```

### Key pair 2: Create the key exchange key (KEK)


The private KEK is used to add keys to the db, which is the list of authorized signatures to boot on the system. 

**To create the KEK**

1. Create the key.

   ```
   openssl req -newkey rsa:4096 -nodes -keyout KEK.key -new -x509 -sha256 -days 3650 -subj "/CN=Key Exchange Key/" -out KEK.crt
   ```

1. Create the certificate.

   ```
   openssl x509 -outform DER -in KEK.crt -out KEK.cer
   ```

1. Convert the certificate into a UEFI signature list.

   ```
   cert-to-efi-sig-list -g "$(< GUID.txt)" KEK.crt KEK.esl
   ```

1. Sign the signature list with the private PK.

   ```
   sign-efi-sig-list -g "$(< GUID.txt)" -k PK.key -c PK.crt KEK KEK.esl KEK.auth
   ```

### Key pair 3: Create the signature database (db)


The db list contains authorized keys that are authorized to be booted on the system. To modify the list, the private KEK is necessary. Boot images will be signed with the private key that is created in this step.

**To create the db**

1. Create the key.

   ```
   openssl req -newkey rsa:4096 -nodes -keyout db.key -new -x509 -sha256 -days 3650 -subj "/CN=Signature Database key/" -out db.crt
   ```

1. Create the certificate.

   ```
   openssl x509 -outform DER -in db.crt -out db.cer
   ```

1. Convert the certificate into a UEFI signature list.

   ```
   cert-to-efi-sig-list -g "$(< GUID.txt)" db.crt db.esl
   ```

1. Sign the signature list with the private KEK.

   ```
   sign-efi-sig-list -g "$(< GUID.txt)" -k KEK.key -c KEK.crt db db.esl db.auth
   ```

### Sign the boot image (kernel) with the private key


For Ubuntu 22.04, the following images require signatures.

```
/boot/efi/EFI/ubuntu/shimx64.efi
/boot/efi/EFI/ubuntu/mmx64.efi
/boot/efi/EFI/ubuntu/grubx64.efi
/boot/vmlinuz
```

**To sign an image**  
Use the following syntax to sign an image.

```
sbsign --key db.key --cert db.crt --output /boot/vmlinuz /boot/vmlinuz
```

**Note**  
You must sign all new kernels. *`/boot/vmlinuz`* will usually symlink to the last installed kernel.

Refer to the documentation for your distribution to find out about your boot chain and required images.

¹ Thanks to the ArchWiki community for all of the work they have done. The commands for creating the PK, creating the KEK, creating the DB, and signing the image are from [Creating keys](https://wiki.archlinux.org/title/Unified_Extensible_Firmware_Interface/Secure_Boot#Creating_keys), authored by the ArchWiki Maintenance Team and/or the ArchWiki contributors.

## Task 2 - Option A: Add keys to the variable store from within the instance


After you have created the [three key pairs](#uefi-secure-boot-create-three-key-pairs), you can connect to your instance and add the keys to the variable store from within the instance by completing the following steps. Alternatively, complete the steps in [Task 2 - Option B: Create a binary blob containing a pre-filled variable store](#uefi-secure-boot-optionB).

**Topics**
+ [

### Step 1: Launch an instance that will support UEFI Secure Boot
](#step1-launch-uefi-sb)
+ [

### Step 2: Configure an instance to support UEFI Secure Boot
](#step2-launch-uefi-sb)
+ [

### Step 3: Create an AMI from the instance
](#step3-launch-uefi-sb)

### Step 1: Launch an instance that will support UEFI Secure Boot


When you [launch an instance](LaunchingAndUsingInstances.md) with the following prerequisites, the instance will then be ready to be configured to support UEFI Secure Boot. You can only enable support for UEFI Secure Boot on an instance at launch; you can't enable it later.

**Prerequisites**
+ **AMI** – The Linux AMI must support UEFI boot mode. To verify that the AMI supports UEFI boot mode, the AMI boot mode parameter must be **uefi**. For more information, see [Determine the boot mode parameter of an Amazon EC2 AMI](ami-boot-mode.md).

  Note that AWS only provides Linux AMIs configured to support UEFI for Graviton-based instance types. AWS currently does not provide x86\$164 Linux AMIs that support UEFI boot mode. You can configure your own AMI to support UEFI boot mode for all architectures. To configure your own AMI to support UEFI boot mode, you must perform a number of configuration steps on your own AMI. For more information, see [Set the boot mode of an Amazon EC2 AMI](set-ami-boot-mode.md).
+ **Instance type** – All virtualized instance types that support UEFI also support UEFI Secure Boot. Bare metal instance types do not support UEFI Secure Boot. For the instance types that support UEFI Secure Boot, see [Requirements for UEFI boot mode](launch-instance-boot-mode.md).
+ Launch your instance after the release of UEFI Secure Boot. Only instances launched after May 10, 2022 (when UEFI Secure Boot was released) can support UEFI Secure Boot.

After you’ve launched your instance, you can verify that it is ready to be configured to support UEFI Secure Boot (in other words, you can proceed to [Step 2](#step2-launch-uefi-sb)) by checking whether UEFI data is present. The presence of UEFI data indicates that non-volatile data is persisted.

**To verify whether your instance is ready for Step 2**  
Use the [https://docs.aws.amazon.com/cli/latest/reference/ec2/get-instance-uefi-data.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/get-instance-uefi-data.html) command and specify the instance ID.

```
aws ec2 get-instance-uefi-data --instance-id i-1234567890abcdef0
```

The instance is ready for Step 2 if UEFI data is present in the output. If the output is empty, the instance cannot be configured to support UEFI Secure Boot. This can happen if your instance was launched before UEFI Secure Boot support became available. Launch a new instance and try again.

### Step 2: Configure an instance to support UEFI Secure Boot


#### Enroll the key pairs in your UEFI variable store on the instance


**Warning**  
You must sign your boot images *after* you enroll the keys, otherwise you won’t be able to boot your instance.

After you create the signed UEFI signature lists (`PK`, `KEK`, and `db`), they must be enrolled into the UEFI firmware.

Writing to the `PK` variable is possible only if:
+ No PK is enrolled yet, which is indicated if the `SetupMode` variable is `1`. Check this by using the following command. The output is either `1` or `0`.

  ```
  efivar -d -n 8be4df61-93ca-11d2-aa0d-00e098032b8c-SetupMode 
  ```
+ The new PK is signed by the private key of the existing PK.

**To enroll the keys in your UEFI variable store**  
The following commands must be run on the instance.

If SetupMode is enabled (the value is `1`), the keys can be enrolled by running the following commands on the instance:

```
[ec2-user ~]$ efi-updatevar -f db.auth db
```

```
[ec2-user ~]$ efi-updatevar -f KEK.auth KEK
```

```
[ec2-user ~]$ efi-updatevar -f PK.auth PK
```

**To verify that UEFI Secure Boot is enabled**  
To verify that UEFI Secure Boot is enabled, follow the steps in [Verify whether an Amazon EC2 instance is enabled for UEFI Secure Boot](verify-uefi-secure-boot.md).

You can now export your UEFI variable store with the [https://docs.aws.amazon.com/cli/latest/reference/ec2/get-instance-uefi-data.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/get-instance-uefi-data.html) CLI command, or you continue to the next step and sign your boot images to reboot into a UEFI Secure Boot-enabled instance.

### Step 3: Create an AMI from the instance


To create an AMI from the instance, you can use the console or the `CreateImage` API, CLI, or SDKs. For the console instructions, see [Create an Amazon EBS-backed AMI](creating-an-ami-ebs.md). For the API instructions, see [CreateImage](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateImage.html).

**Note**  
The `CreateImage` API automatically copies the UEFI variable store of the instance to the AMI. The console uses the `CreateImage` API. After you launch instances using this AMI, the instances will have the same UEFI variable store.

## Task 2 - Option B: Create a binary blob containing a pre-filled variable store


After you have created the [three key pairs](#uefi-secure-boot-create-three-key-pairs), you can create a binary blob containing a pre-filled variable store containing the UEFI Secure Boot keys. Alternatively, complete the steps in [Task 2 - Option A: Add keys to the variable store from within the instance](#uefi-secure-boot-optionA).

**Warning**  
You must sign your boot images *before* you enroll the keys, otherwise you won’t be able to boot your instance.

**Topics**
+ [

### Step 1: Create a new variable store or update an existing one
](#uefi-secure-boot-create-or-update-variable)
+ [

### Step 2: Upload the binary blob on AMI creation
](#uefi-secure-boot-upload-binary-blob-on-ami-creation)

### Step 1: Create a new variable store or update an existing one


You can create the variable store *offline* without a running instance by using the python-uefivars tool. The tool can create a new variable store from your keys. The script currently supports the EDK2 format, the AWS format, and a JSON representation that is easier to edit with higher-level tooling.

**To create the variable store offline without a running instance**

1. Download the tool at the following link.

   ```
   https://github.com/awslabs/python-uefivars
   ```

1. Create a new variable store from your keys by running the following command. This will create a base64-encoded binary blob in *your\$1binary\$1blob*.bin. The tool also supports updating a binary blob via the `-I` parameter.

   ```
   ./uefivars.py -i none -o aws -O your_binary_blob.bin -P PK.esl -K KEK.esl --db db.esl --dbx dbx.esl
   ```

### Step 2: Upload the binary blob on AMI creation


Use [https://docs.aws.amazon.com/cli/latest/reference/ec2/register-image.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/register-image.html) to pass your UEFI variable store data. For the `--uefi-data` parameter, specify your binary blob, and for the `--boot-mode` parameter, specify `uefi`.

```
aws ec2 register-image \
    --name uefi_sb_tpm_register_image_test \
    --uefi-data $(cat your_binary_blob.bin) \
    --block-device-mappings "DeviceName=/dev/sda1,Ebs= {SnapshotId=snap-0123456789example,DeleteOnTermination=true}" \
    --architecture x86_64 \
    --root-device-name /dev/sda1 \
    --virtualization-type hvm \
    --ena-support \
    --boot-mode uefi
```

# Create the AWS binary blob for UEFI Secure Boot
Create the AWS binary blob

You can use the following steps to customize the UEFI Secure Boot variables during AMI creation. The KEK that is used in these steps is current as of September 2021. If Microsoft updates the KEK, you must use the latest KEK.

**To create the AWS binary blob**

1. Create an empty PK signature list.

   ```
   touch empty_key.crt
   cert-to-efi-sig-list empty_key.crt PK.esl
   ```

1. Download the KEK certificates.

   ```
   https://go.microsoft.com/fwlink/?LinkId=321185
   ```

1. Wrap the KEK certificates in a UEFI signature list (`siglist`).

   ```
   sbsiglist --owner 77fa9abd-0359-4d32-bd60-28f4e78f784b --type x509 --output MS_Win_KEK.esl MicCorKEKCA2011_2011-06-24.crt 
   ```

1. Download Microsoft's db certificates.

   ```
   https://www.microsoft.com/pkiops/certs/MicWinProPCA2011_2011-10-19.crt
   https://www.microsoft.com/pkiops/certs/MicCorUEFCA2011_2011-06-27.crt
   ```

1. Generate the db signature list.

   ```
   sbsiglist --owner 77fa9abd-0359-4d32-bd60-28f4e78f784b --type x509 --output MS_Win_db.esl MicWinProPCA2011_2011-10-19.crt
   sbsiglist --owner 77fa9abd-0359-4d32-bd60-28f4e78f784b --type x509 --output MS_UEFI_db.esl MicCorUEFCA2011_2011-06-27.crt
   cat MS_Win_db.esl MS_UEFI_db.esl > MS_db.esl
   ```

1. The Unified Extensible Firmware Interface Forum no longer provides the DBX files. They are now provided by Microsoft on GitHub. Download the latest DBX update from the Microsoft Secure Boot updates repository at [ https://github.com/microsoft/secureboot\$1objects](https://github.com/microsoft/secureboot_objects).

1. Unpack the signed update-binary.

   Create `SplitDbxContent.ps1` with the script content below. Alternatively, you can install the script from [ PowerShell Gallery](https://www.powershellgallery.com/packages/SplitDbxContent/1.0) using `Install-Script -Name SplitDbxContent`.

   ```
   <#PSScriptInfo
    
   .VERSION 1.0
    
   .GUID ec45a3fc-5e87-4d90-b55e-bdea083f732d
    
   .AUTHOR Microsoft Secure Boot Team
    
   .COMPANYNAME Microsoft
    
   .COPYRIGHT Microsoft
    
   .TAGS Windows Security
    
   .LICENSEURI
    
   .PROJECTURI
    
   .ICONURI
    
   .EXTERNALMODULEDEPENDENCIES
    
   .REQUIREDSCRIPTS
    
   .EXTERNALSCRIPTDEPENDENCIES
    
   .RELEASENOTES
   Version 1.0: Original published version.
    
   #>
   
   <#
   .DESCRIPTION
    Splits a DBX update package into the new DBX variable contents and the signature authorizing the change.
    To apply an update using the output files of this script, try:
    Set-SecureBootUefi -Name dbx -ContentFilePath .\content.bin -SignedFilePath .\signature.p7 -Time 2010-03-06T19:17:21Z -AppendWrite'
   .EXAMPLE
   .\SplitDbxAuthInfo.ps1 DbxUpdate_x64.bin
   #>
   
   
   # Get file from script input
   $file  = Get-Content -Encoding Byte $args[0]
   
   # Identify file signature
   $chop = $file[40..($file.Length - 1)]
   if (($chop[0] -ne 0x30) -or ($chop[1] -ne 0x82 )) {
       Write-Error "Cannot find signature"
       exit 1
   }
   
   # Signature is known to be ASN size plus header of 4 bytes
   $sig_length = ($chop[2] * 256) + $chop[3] + 4
   $sig = $chop[0..($sig_length - 1)]
   
   if ($sig_length -gt ($file.Length + 40)) {
       Write-Error "Signature longer than file size!"
       exit 1
   }
   
   # Content is everything else
   $content = $file[0..39] + $chop[$sig_length..($chop.Length - 1)]
   
   # Write signature and content to files
   Set-Content -Encoding Byte signature.p7 $sig
   Set-Content -Encoding Byte content.bin $content
   ```

   Use the script to unpack the signed DBX files.

   ```
   PS C:\Windows\system32> SplitDbxContent.ps1 .\dbx.bin
   ```

   This produces two files — `signature.p7` and `content.bin`. Use `content.bin` in the next step.

1. Build a UEFI variable store using the `uefivars.py` script.

   ```
   ./uefivars.py -i none -o aws -O uefiblob-microsoft-keys-empty-pk.bin -P ~/PK.esl -K ~/MS_Win_KEK.esl --db ~/MS_db.esl  --dbx ~/content.bin 
   ```

1. Check the binary blob and the UEFI variable store.

   ```
   ./uefivars.py -i aws -I uefiblob-microsoft-keys-empty-pk.bin -o json | less
   ```

1. You can update the blob by passing it to the same tool again.

   ```
   ./uefivars.py -i aws -I uefiblob-microsoft-keys-empty-pk.bin -o aws -O uefiblob-microsoft-keys-empty-pk.bin -P ~/PK.esl -K ~/MS_Win_KEK.esl --db ~/MS_db.esl  --dbx ~/content.bin
   ```

   Expected output

   ```
   Replacing PK
   Replacing KEK
   Replacing db
   Replacing dbx
   ```

# Use encryption with EBS-backed AMIs
AMI encryption

AMIs that are backed by Amazon EBS snapshots can take advantage of Amazon EBS encryption. Snapshots of both data and root volumes can be encrypted and attached to an AMI. You can launch instances and copy images with full EBS encryption support included. Encryption parameters for these operations are supported in all Regions where AWS KMS is available.

EC2 instances with encrypted EBS volumes are launched from AMIs in the same way as other instances. In addition, when you launch an instance from an AMI backed by unencrypted EBS snapshots, you can encrypt some or all of the volumes during launch. 

Like EBS volumes, snapshots in AMIs can be encrypted by either your default AWS KMS key, or to a customer managed key that you specify. You must in all cases have permission to use the selected KMS key.

AMIs with encrypted snapshots can be shared across AWS accounts. For more information, see [Understand shared AMI usage in Amazon EC2](sharing-amis.md).

**Topics**
+ [

## Instance-launching scenarios
](#AMI-encryption-launch)
+ [

## Image-copying scenarios
](#AMI-encryption-copy)

## Instance-launching scenarios




Amazon EC2 instances are launched from AMIs using the `RunInstances` action with parameters supplied through block device mapping, either by means of the AWS Management Console or directly using the Amazon EC2 API or CLI. For more information, see [Block device mappings for volumes on Amazon EC2 instances](block-device-mapping-concepts.md). For examples of controlling block device mapping from the AWS CLI, see [Launch, List, and Terminate EC2 Instances](https://docs.aws.amazon.com/cli/latest/userguide/cli-services-ec2-instances.html).

By default, without explicit encryption parameters, a `RunInstances` action maintains the existing encryption state of an AMI's source snapshots while restoring EBS volumes from them. If encryption by default is enabled, all volumes created from the AMI (whether from encrypted or unencrypted snapshots) are encrypted. If encryption by default is not enabled, the instance maintains the encryption state of the AMI.

You can also launch an instance and simultaneously apply a new encryption state to the resulting volumes by supplying encryption parameters. Consequently, the following behaviors are observed:

**Launch with no encryption parameters**
+ An unencrypted snapshot is restored to an unencrypted volume, unless encryption by default is enabled, in which case all the newly created volumes will be encrypted.
+ An encrypted snapshot that you own is restored to a volume that is encrypted to the same KMS key.
+ An encrypted snapshot that you do not own (for example, the AMI is shared with you) is restored to a volume that is encrypted by your AWS account's default KMS key.

The default behaviors can be overridden by supplying encryption parameters. The available parameters are `Encrypted` and `KmsKeyId`. Setting only the `Encrypted` parameter results in the following:

**Instance launch behaviors with `Encrypted` set, but no `KmsKeyId` specified**
+ An unencrypted snapshot is restored to an EBS volume that is encrypted by your AWS account's default KMS key.
+ An encrypted snapshot that you own is restored to an EBS volume encrypted by the same KMS key. (In other words, the `Encrypted` parameter has no effect.)
+ An encrypted snapshot that you do not own (i.e., the AMI is shared with you) is restored to a volume that is encrypted by your AWS account's default KMS key. (In other words, the `Encrypted` parameter has no effect.)

Setting both the `Encrypted` and `KmsKeyId` parameters allows you to specify a non-default KMS key for an encryption operation. The following behaviors result:

**Instance with both `Encrypted` and `KmsKeyId` set**
+ An unencrypted snapshot is restored to an EBS volume encrypted by the specified KMS key.
+ An encrypted snapshot is restored to an EBS volume encrypted not to the original KMS key, but instead to the specified KMS key.

Submitting a `KmsKeyId` without also setting the `Encrypted` parameter results in an error.

The following sections provide examples of launching instances from AMIs using non-default encryption parameters. In each of these scenarios, parameters supplied to the `RunInstances` action result in a change of encryption state during restoration of a volume from a snapshot.

For information about using the console to launch an instance from an AMI, see [Launch an Amazon EC2 instance](LaunchingAndUsingInstances.md).

### Encrypt a volume during launch


In this example, an AMI backed by an unencrypted snapshot is used to launch an EC2 instance with an encrypted EBS volume.

![\[Launch instance and encrypt volume on the fly.\]](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/images/ami-launch-convert.png)


The `Encrypted` parameter alone results in the volume for this instance being encrypted. Providing a `KmsKeyId` parameter is optional. If no KMS key ID is specified, the AWS account's default KMS key is used to encrypt the volume. To encrypt the volume to a different KMS key that you own, supply the `KmsKeyId` parameter. 

### Re-encrypt a volume during launch


In this example, an AMI backed by an encrypted snapshot is used to launch an EC2 instance with an EBS volume encrypted by a new KMS key. 

![\[Launch instance and re-encrypt volume on the fly.\]](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/images/ami-launch-encrypted.png)


If you own the AMI and supply no encryption parameters, the resulting instance has a volume encrypted by the same KMS key as the snapshot. If the AMI is shared rather than owned by you, and you supply no encryption parameters, the volume is encrypted by your default KMS key. With encryption parameters supplied as shown, the volume is encrypted by the specified KMS key.

### Change encryption state of multiple volumes during launch


In this more complex example, an AMI backed by multiple snapshots (each with its own encryption state) is used to launch an EC2 instance with a newly encrypted volume and a re-encrypted volume.

![\[Encrypt and re-encrypt multiple volumes during launch.\]](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/images/ami-launch-mixed.png)


In this scenario, the `RunInstances` action is supplied with encryption parameters for each of the source snapshots. When all possible encryption parameters are specified, the resulting instance is the same regardless of whether you own the AMI.

## Image-copying scenarios


Amazon EC2 AMIs are copied using the `CopyImage` action, either through the AWS Management Console or directly using the Amazon EC2 API or CLI.

By default, without explicit encryption parameters, a `CopyImage` action maintains the existing encryption state of an AMI's source snapshots during copy. You can also copy an AMI and simultaneously apply a new encryption state to its associated EBS snapshots by supplying encryption parameters. Consequently, the following behaviors are observed:

**Copy with no encryption parameters**
+ An unencrypted snapshot is copied to another unencrypted snapshot, unless encryption by default is enabled, in which case all the newly created snapshots will be encrypted.
+ An encrypted snapshot that you own is copied to a snapshot encrypted with the same KMS key.
+ An encrypted snapshot that you do not own (that is, the AMI is shared with you) is copied to a snapshot that is encrypted by your AWS account's default KMS key.

All of these default behaviors can be overridden by supplying encryption parameters. The available parameters are `Encrypted` and `KmsKeyId`. Setting only the `Encrypted` parameter results in the following:

**Copy-image behaviors with `Encrypted` set, but no `KmsKeyId` specified**
+ An unencrypted snapshot is copied to a snapshot encrypted by the AWS account's default KMS key.
+ An encrypted snapshot is copied to a snapshot encrypted by the same KMS key. (In other words, the `Encrypted` parameter has no effect.)
+ An encrypted snapshot that you do not own (i.e., the AMI is shared with you) is copied to a volume that is encrypted by your AWS account's default KMS key. (In other words, the `Encrypted` parameter has no effect.)

Setting both the `Encrypted` and `KmsKeyId` parameters allows you to specify a customer managed KMS key for an encryption operation. The following behaviors result:

**Copy-image behaviors with both `Encrypted` and `KmsKeyId` set**
+ An unencrypted snapshot is copied to a snapshot encrypted by the specified KMS key.
+ An encrypted snapshot is copied to a snapshot encrypted not to the original KMS key, but instead to the specified KMS key.

Submitting a `KmsKeyId` without also setting the `Encrypted` parameter results in an error.

The following section provides an example of copying an AMI using non-default encryption parameters, resulting in a change of encryption state.

For detailed instructions using the console, see [Copy an Amazon EC2 AMI](CopyingAMIs.md).

### Encrypt an unencrypted image during copy


In this scenario, an AMI backed by an unencrypted root snapshot is copied to an AMI with an encrypted root snapshot. The `CopyImage` action is invoked with two encryption parameters, including a customer managed key. As a result, the encryption status of the root snapshot changes, so that the target AMI is backed by a root snapshot containing the same data as the source snapshot, but encrypted using the specified key. You incur storage costs for the snapshots in both AMIs, as well as charges for any instances you launch from either AMI.

**Note**  
Enabling encryption by default has the same effect as setting the `Encrypted` parameter to `true` for all snapshots in the AMI.

![\[Copy AMI and encrypt snapshot on the fly\]](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/images/ami-to-ami-convert.png)


Setting the `Encrypted` parameter encrypts the single snapshot for this instance. If you do not specify the `KmsKeyId` parameter, the default customer managed key is used to encrypt the snapshot copy.

**Note**  
You can also copy an image with multiple snapshots and configure the encryption state of each individually.

# Understand shared AMI usage in Amazon EC2
Shared AMIs

*A shared AMI* is an AMI that a developer created and made available for others to use. One of the easiest ways to get started with Amazon EC2 is to use a shared AMI that has the components you need and then add custom content. You can also create your own AMIs and share them with others. 

You use a shared AMI at your own risk. Amazon can't vouch for the integrity or security of AMIs shared by other Amazon EC2 users. Therefore, you should treat shared AMIs as you would any foreign code that you might consider deploying in your own data center, and perform the appropriate due diligence. We recommend that you get an AMI from a trusted source, such as a verified provider.

## Verified provider


In the Amazon EC2 console, public AMIs that are owned by Amazon or a verified Amazon partner are marked **Verified provider**.

You can also use the [describe-images](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) AWS CLI command to identify the public AMIs that come from a verified provider. Public images that are owned by Amazon or a verified partner have an aliased owner, which is either `amazon`, `aws-backup-vault`, or `aws-marketplace`. In the CLI output, these values appear for `ImageOwnerAlias`. Other users can't alias their AMIs. This enables you to easily find AMIs from Amazon or verified partners.

To become a verified provider, you must register as a seller on the AWS Marketplace. Once registered, you can list your AMI on the AWS Marketplace. For more information, see [Getting started as a seller](https://docs.aws.amazon.com/marketplace/latest/userguide/user-guide-for-sellers.html) and [AMI-based products](https://docs.aws.amazon.com/marketplace/latest/userguide/ami-products.html) in the *AWS Marketplace Seller Guide*.

**Topics**
+ [

## Verified provider
](#verified-ami-provider)
+ [

# Find shared AMIs to use for Amazon EC2 instances
](usingsharedamis-finding.md)
+ [

# Prepare to use shared AMIs for Linux
](usingsharedamis-confirm.md)
+ [

# Control the discovery and use of AMIs in Amazon EC2 with Allowed AMIs
](ec2-allowed-amis.md)
+ [

# Make your AMI publicly available for use in Amazon EC2
](sharingamis-intro.md)
+ [

# Understand block public access for AMIs
](block-public-access-to-amis.md)
+ [

# Share an AMI with organizations and organizational units
](share-amis-with-organizations-and-OUs.md)
+ [

# Share an AMI with specific AWS accounts
](sharingamis-explicit.md)
+ [

# Cancel having an AMI shared with your AWS account
](cancel-sharing-an-AMI.md)
+ [

# Recommendations for creating shared Linux AMIs
](building-shared-amis.md)

**If you're looking for information about other topics**
+ For information about creating an AMI, see [Create an Amazon S3-backed AMI](creating-an-ami-instance-store.md) or [Create an Amazon EBS-backed AMI](creating-an-ami-ebs.md).
+ For information about building, delivering, and maintaining your applications on the AWS Marketplace, see the [AWS Marketplace Documentation](https://docs.aws.amazon.com/marketplace/).

# Find shared AMIs to use for Amazon EC2 instances
Find shared AMIs

You can use the Amazon EC2 console or the command line to find public or private shared AMIs to use with your Amazon EC2 instances.

AMIs are a Regional resource. When you search for a shared AMI (public or private), you must search for it from the same Region from which it is shared. To make an AMI available in a different Region, copy the AMI to the Region, and then share it. For more information, see [Copy an Amazon EC2 AMI](CopyingAMIs.md).

------
#### [ Console ]

The console provides an AMI filter field. You can also scope your searches using the filters provided in the **Search** field.

**To find a shared or AMI**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **AMIs**.

1. In the first filter, choose one of the following options:
   + **Private images** – Lists all AMIs that are shared with you.
   + **Public images** – Lists all public AMIs.

1. (Optional) To display only the public images from Amazon, choose the **Search** field and then, from the menu options, choose **Owner alias**, then **=**, and then **amazon**.

1. (Optional) Add filters to scope your search to AMIs that meet your requirements.

**To find a shared public AMI from a [verified provider](sharing-amis.md#verified-ami-provider)**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **AMI Catalog**.

1. Choose **Community AMIs**.

1. In the **Refine results** pane, select **Verified provider**. The **Verified provider** label indicates that the AMIs are from Amazon or a verified partner.

------
#### [ AWS CLI ]

Use the [describe-images](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) command to list AMIs. You can scope the list to the types of AMIs that interest you, as shown in the following examples.

**To list all public AMIs**  
The following command lists all public AMIs, including any public AMIs that you own.

```
aws ec2 describe-images --executable-users all
```

**To list AMIs with explicit launch permissions**  
The following command lists the AMIs for which you have explicit launch permissions. This list does not include any AMIs that you own.

```
aws ec2 describe-images --executable-users self
```

**To list AMIs owned by verified providers**  
The following command lists the AMIs owned by [verified providers](sharing-amis.md#verified-ami-provider). Public AMIs owned by verified providers (either Amazon or verified partners) have an aliased owner, which appears as `amazon`, `aws-backup-vault`, or `aws-marketplace` in the account field. This helps you to easily find AMIs from verified providers. Other users can't alias their AMIs.

```
aws ec2 describe-images \
    --owners amazon aws-marketplace \
    --query 'Images[*].[ImageId]' \
    --output text
```

**To list AMIs owned by an account**  
The following command lists the AMIs owned by the specified AWS account.

```
aws ec2 describe-images --owners 123456789012
```

**To scope AMIs using a filter**  
To reduce the number of displayed AMIs, use a filter to list only the types of AMIs that interest you. For example, use the following filter to display only EBS-backed AMIs.

```
--filters "Name=root-device-type,Values=ebs"
```

------
#### [ PowerShell ]

Use the [Get-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Image.html) cmdlet (Tools for Windows PowerShell) to list AMIs. You can scope the list to the types of AMIs that interest you, as shown in the following examples.

**To list all public AMIs**  
The following command lists all public AMIs, including any public AMIs that you own.

```
Get-EC2Image -ExecutableUser all
```

**To list AMIs with explicit launch permissions**  
The following command lists the AMIs for which you have explicit launch permissions. This list does not include any AMIs that you own.

```
Get-EC2Image -ExecutableUser self
```

**To list AMIs owned by verified providers**  
The following command lists the AMIs owned by [verified providers](sharing-amis.md#verified-ami-provider). Public AMIs owned by verified providers (either Amazon or verified partners) have an aliased owner, which appears as `amazon`, `aws-backup-vault`, or `aws-marketplace` in the account field. This helps you to easily find AMIs from verified providers. Other users can't alias their AMIs.

```
Get-EC2Image -Owner amazon aws-marketplace
```

**To list AMIs owned by an account**  
The following command lists the AMIs owned by the specified AWS account.

```
Get-EC2Image -Owner 123456789012
```

**To scope AMIs using a filter**  
To reduce the number of displayed AMIs, use a filter to list only the types of AMIs that interest you. For example, use the following filter to display only EBS-backed AMIs.

```
-Filter @{Name="root-device-type"; Values="ebs"}
```

------

# Prepare to use shared AMIs for Linux


Before you use a shared AMI for Linux, take the following steps to confirm that there are no pre-installed credentials that would allow unwanted access to your instance by a third party and no pre-configured remote logging that could transmit sensitive data to a third party. Check the documentation for the Linux distribution used by the AMI for information about improving the security of the system.

To ensure that you don't accidentally lose access to your instance, we recommend that you initiate two SSH sessions and keep the second session open until you've removed credentials that you don't recognize and confirmed that you can still log into your instance using SSH.

1. Identify and disable any unauthorized public SSH keys. The only key in the file should be the key you used to launch the AMI. The following command locates `authorized_keys` files:

   ```
   [ec2-user ~]$ sudo find / -name "authorized_keys" -print -exec cat {} \;
   ```

1. Disable password-based authentication for the root user. Open the `sshd_config` file and edit the `PermitRootLogin` line as follows:

   ```
   PermitRootLogin without-password
   ```

   Alternatively, you can disable the ability to log into the instance as the root user:

   ```
   PermitRootLogin No
   ```

   Restart the sshd service.

1. Check whether there are any other users that are able to log in to your instance. Users with superuser privileges are particularly dangerous. Remove or lock the password of any unknown accounts.

1. Check for open ports that you aren't using and running network services listening for incoming connections.

1. To prevent preconfigured remote logging, you should delete the existing configuration file and restart the `rsyslog` service. For example:

   ```
   [ec2-user ~]$ sudo rm /etc/rsyslog.conf
   [ec2-user ~]$ sudo service rsyslog restart
   ```

1. Verify that all cron jobs are legitimate.

If you discover a public AMI that you feel presents a security risk, contact the AWS security team. For more information, see the [AWS Security Center](https://aws.amazon.com/security/).

# Control the discovery and use of AMIs in Amazon EC2 with Allowed AMIs
Allowed AMIs

To control the discovery and use of Amazon Machine Images (AMIs) by users in your AWS account, you can use the *Allowed AMIs* feature. You specify criteria that AMIs must meet to be visible and available within your account. When the criteria are enabled, users launching instances will only see and have access to AMIs that comply with the specified criteria. For example, you can specify a list of trusted AMI providers as the criteria, and only AMIs from these providers will be visible and available for use.

Before enabling the Allowed AMIs settings, you can enable *audit mode* to preview which AMIs will or won't be visible and available for use. This lets you refine the criteria as needed to ensure that only the intended AMIs are visible and available to users in your account. Additionally, use the [describe-instance-image-metadata](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instance-image-metadata.html) command to find instances that were launched with AMIs that don't meet the specified criteria. This information can guide your decision to either update your launch configurations to use compliant AMIs (for example, specifying a different AMI in a launch template) or adjust your criteria to allow these AMIs.

You specify the Allowed AMIs settings at the account level, either directly in the account or by using a declarative policy. These settings must be configured in each AWS Region where you want to control AMI usage. Using a declarative policy allows you to apply the settings across multiple Regions simultaneously, as well as across multiple accounts simultaneously. When a declarative policy is in use, you can't modify the settings directly within an account. This topic describes how to configure the settings directly within an account. For information about using declarative policies, see [Declarative policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_declarative.html) in the *AWS Organizations User Guide*.

**Note**  
The Allowed AMIs feature only controls the discovery and use of public AMIs or AMIs shared with your account. It does not restrict the AMIs owned by your account. Regardless of the criteria you set, the AMIs created by your account are always discoverable and usable by users in your account.

**Key benefits of Allowed AMIs**
+ **Compliance and security**: Users can only discover and use AMIs that meet the specified criteria, reducing the risk of non-compliant AMI usage.
+ **Efficient management**: By reducing the number of allowed AMIs, managing the remaining ones becomes easier and more efficient.
+ **Centralized account-level implementation**: Configure the Allowed AMIs settings at the account level, either directly within the account or through a declarative policy. This provides a centralized and efficient way to control AMI usage across the entire account.

**Topics**
+ [

## How Allowed AMIs works
](#how-allowed-amis-works)
+ [

## Best practices for implementing Allowed AMIs
](#best-practice-for-implementing-allowed-amis)
+ [

## Required IAM permissions
](#iam-permissions-for-allowed-amis)
+ [

# Manage the settings for Allowed AMIs
](manage-settings-allowed-amis.md)

## How Allowed AMIs works


To control which AMIs can be discovered and used in your account, you define a set of criteria against which to evaluate the AMIs. The criteria are made up of one or more `ImageCriterion` as shown in the following diagram. An explanation follows the diagram.

![\[The Allowed AMIs ImageCriteria configuration hierarchy.\]](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/images/ami_allowed-amis-imagecriteria.png)


The configuration has three levels:
+ **1** – Parameter values
  + Multi-value parameters:
    + `ImageProviders`
    + `ImageNames`
    + `MarketplaceProductCodes`

      An AMI can match *any* values within a parameter to be allowed.

      Example: `ImageProviders` = `amazon` **OR** account `111122223333` **OR** account `444455556666` (The evaluation logic for parameter values is not shown in the diagram.)
  + Single-value parameters:
    + `CreationDateCondition`
    + `DeprecationTimeCondition`
+ **2** – `ImageCriterion`
  + Groups multiple parameters with **AND** logic.
  + An AMI must match *all* parameters within an `ImageCriterion` to be allowed.
  + Example: `ImageProviders` = `amazon` **AND** `CreationDateCondition` = 300 days or less
+ **3** – `ImageCriteria`
  + Groups multiple `ImageCriterion` with **OR** logic.
  + An AMI can match *any* `ImageCriterion` to be allowed.
  + Forms the complete configuration against which AMIs are evaluated. 

**Topics**
+ [

### Allowed AMIs parameters
](#allowed-amis-criteria)
+ [

### Allowed AMIs configuration
](#allowed-amis-json-configuration)
+ [

### How criteria are evaluated
](#how-allowed-amis-criteria-are-evaluated)
+ [

### Limits
](#allowed-amis-json-configuration-limits)
+ [

### Allowed AMIs operations
](#allowed-amis-operations)

### Allowed AMIs parameters


The following parameters can be configured to create `ImageCriterion`:

`ImageProviders`  
The AMI providers whose AMIs are allowed.  
Valid values are aliases that are defined by AWS, and AWS account IDs, as follows:  
+ `amazon` – An alias that identifies AMIs created by Amazon or verified providers
+ `aws-marketplace` – An alias that identifies AMIs created by verified providers in the AWS Marketplace
+ `aws-backup-vault` – An alias that identifies backup AMIs that reside in logically air-gapped AWS Backup vault accounts. If you use the AWS Backup logically air-gapped vault feature, ensure this alias is included as an AMI provider.
+ AWS account IDs – One or more 12-digit AWS account IDs
+ `none` – Indicates that only AMIs created by your account can be discovered and used. Public or shared AMIs can't be discovered and used. When specified, no other criteria can be specified.

`ImageNames`  
The names of allowed AMIs, using exact matches or wildcards (`?` or `*`).

`MarketplaceProductCodes`  
The AWS Marketplace product codes for allowed AMIs.

`CreationDateCondition`  
The maximum age for allowed AMIs.

`DeprecationTimeCondition`  
The maximum period since deprecation for allowed AMIs.

For the valid values and constraints for each criterion, see [ImageCriterionRequest](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImageCriterionRequest.html) in the *Amazon EC2 API Reference*.

### Allowed AMIs configuration


The core configuration for Allowed AMIs is the `ImageCriteria` configuration that defines the criteria for allowed AMIs. The following JSON structure shows the parameters that can be specified:

```
{
    "State": "enabled" | "disabled" | "audit-mode",  
    "ImageCriteria" : [
        {
            "ImageProviders": ["string",...],
            "MarketplaceProductCodes": ["string",...],           
            "ImageNames":["string",...],
            "CreationDateCondition" : {
                "MaximumDaysSinceCreated": integer
            },
            "DeprecationTimeCondition" : {
                "MaximumDaysSinceDeprecated": integer
            }
         },
         ...
}
```

#### ImageCriteria example


The following `ImageCriteria` example configures four `ImageCriterion`. An AMI is allowed if it matches any one of these `ImageCriterion`. For information about how the criteria are evaluated, see [How criteria are evaluated](#how-allowed-amis-criteria-are-evaluated).

```
{
    "ImageCriteria": [
        // ImageCriterion 1: Allow AWS Marketplace AMIs with product code "abcdefg1234567890"
        {
            "MarketplaceProductCodes": [
                "abcdefg1234567890"
            ]
        },
        // ImageCriterion 2: Allow AMIs from providers whose accounts are
        // "123456789012" OR "123456789013" AND AMI age is less than 300 days
        {
            "ImageProviders": [
                "123456789012",
                "123456789013"
            ],
            "CreationDateCondition": {
                "MaximumDaysSinceCreated": 300
            }
        },
        // ImageCriterion 3: Allow AMIs from provider whose account is "123456789014" 
        // AND with names following the pattern "golden-ami-*"
        {
            "ImageProviders": [
                "123456789014"
            ],
            "ImageNames": [
                "golden-ami-*"
            ]
        },
        // ImageCriterion 4: Allow AMIs from Amazon or verified providers 
        // AND which aren't deprecated
        {
            "ImageProviders": [
                "amazon"
            ],
            "DeprecationTimeCondition": {
                "MaximumDaysSinceDeprecated": 0
            }
        }
    ]
}
```

### How criteria are evaluated


The following table explains the evaluation rules that determine if an AMI is allowed, showing how the `AND` or `OR` operator is applied at each level:


| Evaluation level | Operator | Requirement to be an Allowed AMI | 
| --- | --- | --- | 
| Parameter values for ImageProviders, ImageNames, and MarketplaceProductCodes | OR | AMI must match at least one value in each parameter list | 
| ImageCriterion | AND | AMI must match all parameters in each ImageCriterion | 
| ImageCriteria | OR | AMI must match any one of the ImageCriterion | 

Using the preceding evaluation rules, let's see how to apply them to the [ImageCriteria example](#allowed-amis-json-configuration-example):
+ `ImageCriterion` 1: Allows AMIs that have the AWS Marketplace product code `abcdefg1234567890`

  `OR`
+ `ImageCriterion` 2: Allows AMIs that meet both of these criteria:
  + Owned by either account `123456789012` `OR` `123456789013`
    + `AND`
  + Created within the last 300 days

  `OR`
+ `ImageCriterion` 3: Allows AMIs that meet both of these criteria:
  + Owned by account `123456789014`
    + `AND`
  + Named with the pattern `golden-ami-*`

  `OR`
+ `ImageCriterion` 4: Allows AMIs that meet both of these criteria:
  + Published by Amazon or verified providers (specified by the `amazon` alias)
    + `AND`
  + Not deprecated (maximum days since deprecation is `0`)

### Limits


The `ImageCriteria` can include up to:
+ 10 `ImageCriterion`

Each `ImageCriterion` can include up to:
+ 200 values for `ImageProviders`
+ 50 values for `ImageNames` 
+ 50 values for `MarketplaceProductCodes` 

**Example of limits**

Using the preceding [ImageCriteria example](#allowed-amis-json-configuration-example):
+ There are 4 `ImageCriterion`. Up to 6 more can be added to the request to reach the limit of 10.
+ In the first `ImageCriterion`, there is 1 value for `MarketplaceProductCodes`. Up to 49 more can be added to this `ImageCriterion` to reach the limit of 50.
+ In the second `ImageCriterion`, there are 2 values for `ImageProviders`. Up to 198 more can be added to this `ImageCriterion` to reach the limit of 200.
+ In the third `ImageCriterion`, there is 1 value for `ImageNames`. Up to 49 more can be added to this `ImageCriterion` to reach the limit of 50.

### Allowed AMIs operations


The Allowed AMIs feature has three operational states for managing the image criteria: **enabled**, **disabled**, and **audit mode**. These allow you to enable or disable the image criteria, or review them as needed.

**Enabled**

When Allowed AMIs is enabled: 
+ The `ImageCriteria` are applied.
+ Only allowed AMIs are discoverable in the EC2 console and by APIs that use images (for example, that describe, copy, store, or perform other actions that use images).
+ Instances can only be launched using allowed AMIs.

**Disabled**

When Allowed AMIs is disabled: 
+ The `ImageCriteria` are not applied.
+ No restrictions are placed on AMI discoverability or usage. 

**Audit mode**

 In audit mode:
+ The `ImageCriteria` are applied, but no restrictions are placed on AMI discoverability or usage.
+ In the EC2 console, for each AMI, the **Allowed image** field displays either **Yes** or **No** to indicate whether the AMI will be discoverable and available to users in the account when Allowed AMIs is enabled.
+ In the command line, the response for the `describe-image` operation includes `"ImageAllowed": true` or `"ImageAllowed": false` to indicate whether the AMI will be discoverable and available to users in the account when Allowed AMIs is enabled.
+ In the EC2 console, the AMI Catalog displays **Not allowed** next to AMIs that won't be discoverable or available to users in the account when Allowed AMIs is enabled.

## Best practices for implementing Allowed AMIs


When implementing Allowed AMIs, consider these best practices to ensure a smooth transition and minimize potential disruptions to your AWS environment.

1. **Enable audit mode**

   Begin by enabling Allowed AMIs in audit mode. This state allows you to see which AMIs would be affected by your criteria without actually restricting access, providing a risk-free evaluation period.

1. **Set Allowed AMIs criteria**

   Carefully establish which AMI providers align with your organization's security policies, compliance requirements, and operational needs.
**Note**  
When using AWS managed services, such as Amazon ECS, Amazon EKS, or AWS Lambda Managed Instances, we recommend specifying the `amazon` alias to allow AMIs created by AWS. These services depend on Amazon-published AMIs to launch instances.   
Be cautious when setting `CreationDateCondition` restrictions for any AMIs. Setting overly restrictive date conditions (for example, AMIs must be less than 5 days old) can cause instance launch failures if the AMIs, whether from AWS or other providers, are not updated within your specified time frame.  
We recommend pairing `ImageNames` with `ImageProviders` for better control and specificity. Using `ImageNames` alone might not uniquely identify an AMI.

1. **Check for impact on expected business processes**

   You can use the console or the CLI to identify any instances that were launched with AMIs that don't meet the specified criteria. This information can guide your decision to either update your launch configurations to use compliant AMIs (for example, specifying a different AMI in a launch template) or adjust your criteria to allow these AMIs.

   Console: Use the [ec2-instance-launched-with-allowed-ami](https://docs.aws.amazon.com/config/latest/developerguide/ec2-instance-launched-with-allowed-ami.html) AWS Config rule to check if running or stopped instances were launched with AMIs that meet your Allowed AMIs criteria. The rule is **NON\$1COMPLIANT** if an AMI doesn't meet the Allowed AMIs criteria, and **COMPLIANT** if it does. The rule only operates when the Allowed AMIs setting is set to **enabled** or **audit mode**.

   CLI: Run the [describe-instance-image-metadata](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instance-image-metadata.html) command and filter the response to identify any instances that were launched with AMIs that don't meet the specified criteria.

   For the console and CLI instructions, see [Find instances launched from AMIs that aren't allowed](manage-settings-allowed-amis.md#identify-instances-with-allowed-AMIs).

1. **Enable Allowed AMIs**

   Once you've confirmed that the criteria will not adversely affect expected business processes, enable Allowed AMIs.

1. **Monitor instance launches**

   Continue to monitor instance launches from AMIs across your applications and the AWS managed services you use, such as Amazon EMR, Amazon ECR, Amazon EKS, and AWS Elastic Beanstalk. Check for any unexpected issues and make necessary adjustments to the Allowed AMIs criteria.

1. **Pilot new AMIs**

   To test third-party AMIs that do not comply with your current Allowed AMIs settings, AWS recommends the following approaches:
   + Use a separate AWS account: Create an account with no access to your business-critical resources. Ensure that the Allowed AMIs setting is not enabled in this account, or that the AMIs you want to test are explicitly allowed, so that you can test them. 
   + Test in another AWS Region: Use a Region where the third-party AMIs are available, but where you have not yet enabled the Allowed AMIs settings. 

   These approaches help ensure your business-critical resources remain secure while you test new AMIs.

## Required IAM permissions


To use the Allowed AMIs feature, you need the following IAM permissions:
+ `GetAllowedImagesSettings`
+ `EnableAllowedImagesSettings`
+ `DisableAllowedImagesSettings`
+ `ReplaceImageCriteriaInAllowedImagesSettings`

# Manage the settings for Allowed AMIs


You can manage the settings for Allowed AMIs. These settings are per Region per account.

**Topics**
+ [

## Enable Allowed AMIs
](#enable-allowed-amis-criteria)
+ [

## Set the Allowed AMIs criteria
](#update-allowed-amis-criteria)
+ [

## Disable Allowed AMIs
](#disable-allowed-amis-criteria)
+ [

## Get the Allowed AMIs criteria
](#identify-allowed-amis-state-and-criteria)
+ [

## Find AMIs that are allowed
](#identify-amis-that-meet-allowed-amis-criteria)
+ [

## Find instances launched from AMIs that aren't allowed
](#identify-instances-with-allowed-AMIs)

## Enable Allowed AMIs


You can enable Allowed AMIs and specify Allowed AMIs criteria. We recommend that you begin in audit mode, which shows you which AMIs would be affected by the criteria without actually restricting access.

------
#### [ Console ]

**To enable Allowed AMIs**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **Dashboard**.

1. On the **Account attributes** card, under **Settings**, choose **Allowed AMIs**.

1. On the **Allowed AMIs** tab, choose **Manage**.

1. For **Allowed AMIs settings**, choose **Audit mode** or **Enabled**. We recommend that you begin in audit mode, test the criteria, and then return to this step to enable Allowed AMIs.

1. (Optional) For **AMI criteria**, enter the criteria in JSON format.

1. Choose **Update**.

------
#### [ AWS CLI ]

**To enable Allowed AMIs**  
Use the [enable-allowed-images-settings](https://docs.aws.amazon.com/cli/latest/reference/ec2/enable-allowed-images-settings.html) command.

```
aws ec2 enable-allowed-images-settings --allowed-images-settings-state enabled
```

To enable audit mode instead, specify `audit-mode` instead of `enabled`.

```
aws ec2 enable-allowed-images-settings --allowed-images-settings-state audit-mode
```

------
#### [ PowerShell ]

**To enable Allowed AMIs**  
Use the [Enable-EC2AllowedImagesSetting](https://docs.aws.amazon.com/powershell/latest/reference/items/Enable-EC2AllowedImagesSetting.html) cmdlet.

```
Enable-EC2AllowedImagesSetting -AllowedImagesSettingsState enabled
```

To enable audit mode instead, specify `audit-mode` instead of `enabled`.

```
Enable-EC2AllowedImagesSetting -AllowedImagesSettingsState audit-mode
```

------

## Set the Allowed AMIs criteria


After you enable Allowed AMIs, you can set or replace the Allowed AMIs criteria.

For the correct configuration and valid values, see [Allowed AMIs configuration](ec2-allowed-amis.md#allowed-amis-json-configuration) and [Allowed AMIs parameters](ec2-allowed-amis.md#allowed-amis-criteria).

------
#### [ Console ]

**To set the Allowed AMIs criteria**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **Dashboard**.

1. On the **Account attributes** card, under **Settings**, choose **Allowed AMIs**.

1. On the **Allowed AMIs** tab, choose **Manage**.

1. For **AMI criteria**, enter the criteria in JSON format.

1. Choose **Update**.

------
#### [ AWS CLI ]

**To set the Allowed AMIs criteria**  
Use the [replace-image-criteria-in-allowed-images-settings](https://docs.aws.amazon.com/cli/latest/reference/ec2/replace-image-criteria-in-allowed-images-settings.html) command and specify the JSON file that contains the Allowed AMIs criteria.

```
aws ec2 replace-image-criteria-in-allowed-images-settings --cli-input-json file://file_name.json
```

------
#### [ PowerShell ]

**To set the Allowed AMIs criteria**  
Use the [Set-EC2ImageCriteriaInAllowedImagesSetting](https://docs.aws.amazon.com/powershell/latest/reference/items/Set-EC2ImageCriteriaInAllowedImagesSetting.html) cmdlet and specify the JSON file that contains the Allowed AMIs criteria.

```
$imageCriteria = Get-Content -Path .\file_name.json | ConvertFrom-Json
Set-EC2ImageCriteriaInAllowedImagesSetting -ImageCriterion $imageCriteria
```

------

## Disable Allowed AMIs


You can disable Allowed AMIs as follows.

------
#### [ Console ]

**To disable Allowed AMIs**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **Dashboard**.

1. On the **Account attributes** card, under **Settings**, choose **Allowed AMIs**.

1. On the **Allowed AMIs** tab, choose **Manage**.

1. For **Allowed AMIs settings**, choose **Disabled**.

1. Choose **Update**.

------
#### [ AWS CLI ]

**To disable Allowed AMIs**  
Use the [disable-allowed-images-settings](https://docs.aws.amazon.com/cli/latest/reference/ec2/disable-allowed-images-settings.html) command.

```
aws ec2 disable-allowed-images-settings
```

------
#### [ PowerShell ]

**To disable Allowed AMIs**  
Use the [Disable-EC2AllowedImagesSetting](https://docs.aws.amazon.com/powershell/latest/reference/items/Disable-EC2AllowedImagesSetting.html) cmdlet.

```
Disable-EC2AllowedImagesSetting
```

------

## Get the Allowed AMIs criteria


You can get the current state of the Allowed AMIs setting and the Allowed AMIs criteria.

------
#### [ Console ]

**To get the Allowed AMIs state and criteria**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **Dashboard**.

1. On the **Account attributes** card, under **Settings**, choose **Allowed AMIs**.

1. On the **Allowed AMIs** tab, **Allowed AMIs settings** is set to **Enabled**, **Disabled**, or **Audit mode**.

1. If the state of Allowed AMIs is either **Enabled** or **Audit mode**, **AMI criteria**, displays the AMI criteria in JSON format.

------
#### [ AWS CLI ]

**To get the Allowed AMIs state and criteria**  
Use the [get-allowed-images-settings](https://docs.aws.amazon.com/cli/latest/reference/ec2/get-allowed-images-settings.html) command.

```
aws ec2 get-allowed-images-settings
```

In the following example output, the state is `audit-mode` and the image criteria are set in the account.

```
{
    "State": "audit-mode",
    "ImageCriteria": [
        {
            "MarketplaceProductCodes": [
                "abcdefg1234567890"
            ]
        },
        {
            "ImageProviders": [
                "123456789012",
                "123456789013"
            ],
            "CreationDateCondition": {
                "MaximumDaysSinceCreated": 300
            }
        },
        {
            "ImageProviders": [
                "123456789014"
            ],
            "ImageNames": [
                "golden-ami-*"
            ]
        },
        {
            "ImageProviders": [
                "amazon"
            ],
            "DeprecationTimeCondition": {
                "MaximumDaysSinceDeprecated": 0
            }
        }
    ],
    "ManagedBy": "account"
}
```

------
#### [ PowerShell ]

**To get the Allowed AMIs state and criteria**  
Use the [Get-EC2AllowedImagesSetting](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2AllowedImagesSetting.html) cmdlet.

```
Get-EC2AllowedImagesSetting | Select-Object `
    State, `
    ManagedBy, `
    @{Name='ImageProviders'; Expression={($_.ImageCriteria.ImageProviders)}}, `
    @{Name='MarketplaceProductCodes'; Expression={($_.ImageCriteria.MarketplaceProductCodes)}}, `
    @{Name='ImageNames'; Expression={($_.ImageCriteria.ImageNames)}}, `
    @{Name='MaximumDaysSinceCreated'; Expression={($_.ImageCriteria.CreationDateCondition.MaximumDaysSinceCreated)}}, `
    @{Name='MaximumDaysSinceDeprecated'; Expression={($_.ImageCriteria.DeprecationTimeCondition.MaximumDaysSinceDeprecated)}}
```

In the following example output, the state is `audit-mode` and the image criteria are set in the account.

```
State      : audit-mode
ManagedBy  : account
ImageProviders            : {123456789012, 123456789013, 123456789014, amazon}
MarketplaceProductCodes   : {abcdefg1234567890}
ImageNames                : {golden-ami-*}
MaximumDaysSinceCreated  : 300
MaximumDaysSinceDeprecated: 0
```

------

## Find AMIs that are allowed


You can find the AMIs that are allowed or not allowed by the current Allowed AMIs criteria.

**Note**  
Allowed AMIs must be in audit mode.

------
#### [ Console ]

**To check whether an AMI meets the Allowed AMIs criteria**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **AMIs**.

1. Select the AMI.

1. On the **Details** tab (if you selected the checkbox) or in the summary area (if you selected the AMI ID), find the **Allowed image** field.
   + **Yes** – The AMI meets the Allowed AMIs criteria. This AMI will be available to users in your account after you enable Allowed AMIs.
   + **No** – The AMI does not meet the Allowed AMIs criteria.

1. In the navigation pane, choose **AMI Catalog**.

   An AMI marked **Not allowed** indicates an AMI that does not meet the Allowed AMIs criteria. This AMI won't be visible or available to users in your account when Allowed AMIs is enabled.

------
#### [ AWS CLI ]

**To check whether an AMI meets the Allowed AMIs criteria**  
Use the [describe-images](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) command.

```
aws ec2 describe-images \
    --image-id ami-0abcdef1234567890 \
    --query Images[].ImageAllowed \
    --output text
```

The following is example output.

```
True
```

**To find AMIs that meet the Allowed AMIs criteria**  
Use the [describe-images](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) command.

```
aws ec2 describe-images \
    --filters "Name=image-allowed,Values=true" \
    --max-items 10 \
    --query Images[].ImageId
```

The following is example output.

```
ami-000eaaa8be2fd162a
ami-000f82db25e50de8e
ami-000fc21eb34c7a9a6
ami-0010b876f1287d7be
ami-0010b929226fe8eba
ami-0010957836340aead
ami-00112c992a47ba871
ami-00111759e194abcc1
ami-001112565ffcafa5e
ami-0011e45aaee9fba88
```

------
#### [ PowerShell ]

**To check whether an AMI meets the Allowed AMIs criteria**  
Use the [Get-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Image.html) cmdlet.

```
(Get-EC2Image -ImageId ami-0abcdef1234567890).ImageAllowed
```

The following is example output.

```
True
```

**To find AMIs that meet the Allowed AMIs criteria**  
Use the [Get-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Image.html) cmdlet.

```
Get-EC2Image `
    -Filter @{Name="image-allows";Values="true"} `
    -MaxResult 10 | `
    Select ImageId
```

The following is example output.

```
ami-000eaaa8be2fd162a
ami-000f82db25e50de8e
ami-000fc21eb34c7a9a6
ami-0010b876f1287d7be
ami-0010b929226fe8eba
ami-0010957836340aead
ami-00112c992a47ba871
ami-00111759e194abcc1
ami-001112565ffcafa5e
ami-0011e45aaee9fba88
```

------

## Find instances launched from AMIs that aren't allowed


You can identify the instances that were launched using an AMI that does not meet the Allowed AMIs criteria.

------
#### [ Console ]

**To check whether an instance was launched using an AMI that isn't allowed**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **Instances**.

1. Select the instance.

1. On the **Details** tab, under **Instance details**, find **Allowed image**.
   + **Yes** – The AMI meets the Allowed AMIs criteria.
   + **No** – The AMI does not meet the Allowed AMIs criteria.

------
#### [ AWS CLI ]

**To find instances launched using AMIs that aren't allowed**  
Use the [describe-instance-image-metadata](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instance-image-metadata.html) command with the `image-allowed` filter.

```
aws ec2 describe-instance-image-metadata \
    --filters "Name=image-allowed,Values=false" \
    --query "InstanceImageMetadata[*].[InstanceId,ImageMetadata.ImageId]" \
    --output table
```

The following is example output.

```
--------------------------------------------------
|          DescribeInstanceImageMetadata         |
+----------------------+-------------------------+
|  i-08fd74f3f1595fdbd |  ami-09245d5773578a1d6  |
|  i-0b1bf24fd4f297ab9 |  ami-07cccf2bd80ed467f  |
|  i-026a2eb590b4f7234 |  ami-0c0ec0a3a3a4c34c0  |
|  i-006a6a4e8870c828f |  ami-0a70b9d193ae8a799  |
|  i-0781e91cfeca3179d |  ami-00c257e12d6828491  |
|  i-02b631e2a6ae7c2d9 |  ami-0bfddf4206f1fa7b9  |
+----------------------+-------------------------+
```

------
#### [ PowerShell ]

**To find instances launched using AMIs that aren't allowed**  
Use the [Get-EC2InstanceImageMetadata](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2InstanceImageMetadata.html) cmdlet.

```
Get-EC2InstanceImageMetadata `
    -Filter @{Name="image-allowed";Values="false"} | `
    Select InstanceId, @{Name='ImageId'; Expression={($_.ImageMetadata.ImageId)}}
```

The following is example output.

```
InstanceId          ImageId
----------          -------
i-08fd74f3f1595fdbd ami-09245d5773578a1d6
i-0b1bf24fd4f297ab9 ami-07cccf2bd80ed467f
i-026a2eb590b4f7234 ami-0c0ec0a3a3a4c34c0
i-006a6a4e8870c828f ami-0a70b9d193ae8a799
i-0781e91cfeca3179d ami-00c257e12d6828491
i-02b631e2a6ae7c2d9 ami-0bfddf4206f1fa7b9
```

------
#### [ AWS Config ]

You can add the **ec2-instance-launched-with-allowed-ami** AWS Config rule, configure it for your requirements, and then use it to evaluate your instances.

For more information, see [Adding AWS Config rules](https://docs.aws.amazon.com/config/latest/developerguide/evaluate-config_add-rules.html) and [ec2-instance-launched-with-allowed-ami](https://docs.aws.amazon.com/config/latest/developerguide/ec2-instance-launched-with-allowed-ami.html) in the *AWS Config Developer Guide*.

------

# Make your AMI publicly available for use in Amazon EC2
Make your AMI public

You can make your AMI publicly available by sharing it with all AWS accounts.

If you want to prevent the public sharing of your AMIs, you can enable *block public access for AMIs*. This blocks any attempts to make an AMI public, helping to prevent unauthorized access and potential misuse of AMI data. Note that enabling block public access does not affect your AMIs that are already publicly available; they remain publicly available. For more information, see [Understand block public access for AMIs](block-public-access-to-amis.md).

To allow only specific accounts to use your AMI to launch instances, see [Share an AMI with specific AWS accounts](sharingamis-explicit.md).

**Topics**
+ [

## Considerations
](#considerations-for-sharing-public-AMIs)
+ [

## Share an AMI with all AWS accounts (share publicly)
](#share-an-ami-publicly)

## Considerations


Consider the following before making an AMI public.
+ **Ownership** – To make an AMI public, your AWS account must own the AMI.
+ **Region** – AMIs are a Regional resource. When you share an AMI, it is available only in the Region from which you shared it. To make an AMI available in a different Region, copy the AMI to the Region and then share it. For more information, see [Copy an Amazon EC2 AMI](CopyingAMIs.md).
+ **Block public access** – To publicly share an AMI, [block public access for AMIs](block-public-access-to-amis.md) must be disabled in each Region in which the AMI will be publicly shared. After you've publicly shared the AMI, you can re-enable block public access for AMIs to prevent further public sharing of your AMIs.
+ **Some AMIs can't be made public** – If your AMI includes one of the following components, you can't make it public (but you can [share the AMI with specific AWS accounts](sharingamis-explicit.md)):
  + Encrypted volumes
  + Snapshots of encrypted volumes
  + Product codes
+ **Avoid exposing sensitive data** – To avoid exposing sensitive data when you share an AMI, read the security considerations in [Recommendations for creating shared Linux AMIs](building-shared-amis.md) and follow the recommended actions.
+ **Usage** – When you share an AMI, users can only launch instances from the AMI. They can’t delete, share, or modify it. However, after they have launched an instance using your AMI, they can then create an AMI from the instance they launched.
+ **Automatic deprecation** – By default, the deprecation date of all public AMIs is set to two years from the AMI creation date. You can set the deprecation date to earlier than two years. To cancel the deprecation date, or to move the deprecation to a later date, you must make the AMI private by only [sharing it with specific AWS accounts](sharingamis-explicit.md).
+ **Remove obsolete AMIs** – After a public AMI reaches its deprecation date, if no new instances were launched from the AMI for six or more months, AWS eventually removes the public sharing property so that obsolete AMIs don’t appear in the public AMI lists.
+ **Billing** – You are not billed when your AMI is used by other AWS accounts to launch instances. The accounts that launch instances using the AMI are billed for the instances that they launch.

## Share an AMI with all AWS accounts (share publicly)


After you make an AMI public, it is available in **Community AMIs** in the console, which you can access from the **AMI Catalog** in the left navigator in the EC2 console or when launching an instance using the console. Note that it can take a short while for an AMI to appear in **Community AMIs** after you make it public. 

------
#### [ Console ]

**To make an AMI public**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **AMIs**.

1. Select your AMI from the list, and then choose **Actions**, **Edit AMI permissions**.

1. Under **AMI availability**, choose **Public**.

1. Choose **Save changes**.

------
#### [ AWS CLI ]

Each AMI has a `launchPermission` property that controls which AWS accounts, besides the owner's, are allowed to use that AMI to launch instances. By modifying the `launchPermission` property of an AMI, you can make the AMI public (which grants launch permissions to all AWS accounts), or share it with only the AWS accounts that you specify.

You can add or remove account IDs from the list of accounts that have launch permissions for an AMI. To make the AMI public, specify the `all` group. You can specify both public and explicit launch permissions.

**To make an AMI public**

1. Use the [https://docs.aws.amazon.com/cli/latest/reference/ec2/modify-image-attribute.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/modify-image-attribute.html) command as follows to add the `all` group to the `launchPermission` list for the specified AMI.

   ```
   aws ec2 modify-image-attribute \
       --image-id ami-0abcdef1234567890 \
       --launch-permission "Add=[{Group=all}]"
   ```

1. To verify the launch permissions of the AMI, use the [https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-image-attribute.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-image-attribute.html) command.

   ```
   aws ec2 describe-image-attribute \
       --image-id ami-0abcdef1234567890 \
       --attribute launchPermission
   ```

1. (Optional) To make the AMI private again, remove the `all` group from its launch permissions. Note that the owner of the AMI always has launch permissions and is therefore unaffected by this command.

   ```
   aws ec2 modify-image-attribute \
       --image-id ami-0abcdef1234567890 \
       --launch-permission "Remove=[{Group=all}]"
   ```

------
#### [ PowerShell ]

Each AMI has a `launchPermission` property that controls which AWS accounts, besides the owner's, are allowed to use that AMI to launch instances. By modifying the `launchPermission` property of an AMI, you can make the AMI public (which grants launch permissions to all AWS accounts), or share it with only the AWS accounts that you specify.

You can add or remove account IDs from the list of accounts that have launch permissions for an AMI. To make the AMI public, specify the `all` group. You can specify both public and explicit launch permissions.

**To make an AMI public**

1. Use the [https://docs.aws.amazon.com/powershell/latest/reference/items/Edit-EC2ImageAttribute.html](https://docs.aws.amazon.com/powershell/latest/reference/items/Edit-EC2ImageAttribute.html) command as follows to add the `all` group to the `launchPermission` list for the specified AMI.

   ```
   Edit-EC2ImageAttribute `
       -ImageId ami-0abcdef1234567890 `
       -Attribute launchPermission `
       -OperationType add `
       -UserGroup all
   ```

1. To verify the launch permissions of the AMI, use the following [https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2ImageAttribute.html](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2ImageAttribute.html) command.

   ```
   Get-EC2ImageAttribute `
       -ImageId ami-0abcdef1234567890 `
       -Attribute launchPermission
   ```

1. (Optional) To make the AMI private again, remove the `all` group from its launch permissions. Note that the owner of the AMI always has launch permissions and is therefore unaffected by this command.

   ```
   Edit-EC2ImageAttribute `
       -ImageId ami-0abcdef1234567890 `
       -Attribute launchPermission `
       -OperationType remove `
       -UserGroup all
   ```

------

# Understand block public access for AMIs
Block public access for AMIs

To prevent the public sharing of your AMIs, you can enable *block public access for AMIs* at the account level.

When block public access is enabled, any attempt to make an AMI public is automatically blocked. However, if you already have public AMIs, they remain publicly available.

To publicly share AMIs, you must disable block public access. When you’re done sharing, it's best practice to re-enable block public access to prevent any unintended public sharing of your AMIs.

**Note**  
This setting is configured at the account level, either directly in the account or by using a declarative policy. It must be configured in each AWS Region where you want to prevent the public sharing of your AMIs. Using a declarative policy allows you to apply the setting across multiple Regions simultaneously, as well as across multiple accounts simultaneously. When a declarative policy is in use, you can't modify the setting directly within an account. This topic describes how to configure the setting directly within an account. For information about using declarative policies, see [Declarative policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_declarative.html) in the *AWS Organizations User Guide.*

You can restrict IAM permissions to an administrator user so that only they can enable or disable block public access for AMIs.

**Topics**
+ [

## Default settings
](#block-public-access-to-amis-default-settings)
+ [

# Manage the block public access setting for AMIs
](manage-block-public-access-for-amis.md)

## Default settings


The **Block public access for AMIs** setting is either enabled or disabled by default depending on whether your account is new or existing, and whether you have public AMIs. The following table lists the default settings:


| AWS account | Block public access for AMIs default setting | 
| --- | --- | 
| New accounts | Enabled | 
|  Existing accounts with no public AMIs ¹  | Enabled | 
|  Existing accounts with one or more public AMIs  | Disabled | 

¹ If your account had one or more public AMIs on or after July 15, 2023, **Block public access for AMIs** is disabled by default for your account, even if you subsequently made all the AMIs private.

# Manage the block public access setting for AMIs


You can manage the block public access setting for your AMIs to control whether they can be publicly shared. You can enable, disable, or view the current block public access state for your AMIs using the Amazon EC2 console or the AWS CLI.

## View the block public access state for AMIs


To see whether the public sharing of your AMIs is blocked in your account, you can view the state for block public access for AMIs. You must view the state in each AWS Region in which you want to see whether the public sharing of your AMIs is blocked.

**Required permissions**  
To get the current block public access setting for AMIs, you must have the `GetImageBlockPublicAccessState` IAM permission.

------
#### [ Console ]

**To view the block public access state for AMIs in the specified Region**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. From the navigation bar (at the top of the screen), select the Region in which to view the block public access state for AMIs.

1. In the navigation pane, choose **Dashboard**.

1. On the **Account attributes** card, under **Settings**, choose **Data protection and security**.

1. Under **Block public access for AMIs**, check the **Public access** field. The value is either **New public sharing blocked** or **New public sharing allowed**.

------
#### [ AWS CLI ]

**To get the block public access state for AMIs**  
Use the [ get-image-block-public-access-state](https://docs.aws.amazon.com/cli/latest/reference/ec2/get-image-block-public-access-state.html) command. The value is either `block-new-sharing` or `unblocked`.

**Example: For a specific Region**

```
aws ec2 get-image-block-public-access-state --region us-east-1
```

The `ManagedBy` field indicates the entity that configured the setting. In this example, `account` indicates that the setting was configured directly in the account. A value of `declarative-policy` would mean the setting was configured by a declarative policy. For more information, see [Declarative policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_declarative.html) in the *AWS Organizations User Guide*.

```
{
    "ImageBlockPublicAccessState": "block-new-sharing",
    "ManagedBy": "account"
}
```

**Example: For all Regions in your account**

```
echo -e "Region   \t Public Access State" ; \
echo -e "-------------- \t ----------------------" ; \
for region in $(
    aws ec2 describe-regions \
        --region us-east-1 \
        --query "Regions[*].[RegionName]" \
        --output text
    ); 
    do (output=$(
        aws ec2 get-image-block-public-access-state \
            --region $region \
            --output text)
        echo -e "$region \t $output" 
    );
done
```

The following is example output.

```
Region           Public Access State
--------------   ----------------------
ap-south-1       block-new-sharing
eu-north-1       unblocked
eu-west-3        block-new-sharing
...
```

------
#### [ PowerShell ]

**To get the block public access state for AMIs**  
Use the [Get-EC2ImageBlockPublicAccessState](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2ImageBlockPublicAccessState.html) cmdlet. The value is either `block-new-sharing` or `unblocked`.

**Example: For a specific Region**

```
Get-EC2ImageBlockPublicAccessState -Region us-east-1
```

The following is example output.

```
block-new-sharing
```

**Example: For all Regions in your account**

```
(Get-EC2Region).RegionName | `
    ForEach-Object {
        [PSCustomObject]@{
            Region   = $_
            PublicAccessState = (Get-EC2ImageBlockPublicAccessState -Region $_)
        }
} | `
Format-Table -AutoSize
```

The following is example output.

```
Region         PublicAccessState
------         -----------------
ap-south-1     block-new-sharing
eu-north-1     block-new-sharing
eu-west-3      block-new-sharing
...
```

------

## Enable block public access for AMIs


To prevent the public sharing of your AMIs, enable block public access for AMIs at the account level. You must enable block public access for AMIs in each AWS Region in which you want to prevent the public sharing of your AMIs. If you already have public AMIs, they will remain publicly available.

**Required permissions**  
To enable the block public access setting for AMIs, you must have the `EnableImageBlockPublicAccess` IAM permission.

**Considerations**
+ It can take up to 10 minutes to configure this setting. During this time, if you describe the public access state, the response is `unblocked`. When the configuration is completed, the response is `block-new-sharing`.

------
#### [ Console ]

**To enable block public access for AMIs in the specified Region**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. From the navigation bar (at the top of the screen), select the Region in which to enable block public access for AMIs.

1. In the navigation pane, choose **Dashboard**.

1. On the **Account attributes** card, under **Settings**, choose **Data protection and security**.

1. Under **Block public access for AMIs**, choose **Manage**.

1. Select the **Block new public sharing** checkbox, and then choose **Update**.

------
#### [ AWS CLI ]

**To enable block public access for AMIs**  
Use the [enable-image-block-public-access](https://docs.aws.amazon.com/cli/latest/reference/ec2/enable-image-block-public-access.html) command.

**Example: For a specific Region**

```
aws ec2 enable-image-block-public-access \
--region us-east-1 \
--image-block-public-access-state block-new-sharing
```

The following is example output.

```
{ 
    "ImageBlockPublicAccessState": "block-new-sharing"
}
```

**Example: For all Regions in your account**

```
echo -e "Region   \t Public Access State" ; \
echo -e "-------------- \t ----------------------" ; \
for region in $(
    aws ec2 describe-regions \
        --region us-east-1 \
        --query "Regions[*].[RegionName]" \
        --output text
    ); 
    do (output=$(
        aws ec2 enable-image-block-public-access \
            --region $region \
            --image-block-public-access-state block-new-sharing \
            --output text)
        echo -e "$region \t $output" 
    );
done
```

The following is example output.

```
Region           Public Access State
--------------   ----------------------
ap-south-1       block-new-sharing
eu-north-1       block-new-sharing
eu-west-3        block-new-sharing
...
```

------
#### [ PowerShell ]

**To enable block public access for AMIs**  
Use the [Enable-EC2ImageBlockPublicAccess](https://docs.aws.amazon.com/powershell/latest/reference/items/Enable-EC2ImageBlockPublicAccess.html) command.

**Example: For a specific Region**

```
Enable-EC2ImageBlockPublicAccess `
    -Region us-east-1 `
    -ImageBlockPublicAccessState block-new-sharing
```

The following is example output.

```
Value
-----
block-new-sharing
```

**Example: For all Regions in your account**

```
(Get-EC2Region).RegionName | `
    ForEach-Object {
    [PSCustomObject]@{
        Region            = $_
        PublicAccessState = (
        Enable-EC2ImageBlockPublicAccess `
         -Region $_ `
         -ImageBlockPublicAccessState block-new-sharing)
    }
} | `
Format-Table -AutoSize
```

The following is example output.

```
Region         PublicAccessState
------         -----------------
ap-south-1     block-new-sharing
eu-north-1     block-new-sharing
eu-west-3      block-new-sharing
...
```

------

## Disable block public access for AMIs


To allow the users in your account to publicly share your AMIs, disable block public access at the account level. You must disable block public access for AMIs in each AWS Region in which you want to allow the public sharing of your AMIs.

**Required permissions**  
To disable the block public access setting for AMIs, you must have the `DisableImageBlockPublicAccess` IAM permission.

**Considerations**
+ It can take up to 10 minutes to configure this setting. During this time, if you describe the public access state, the response is `block-new-sharing`. When the configuration is completed, the response is `unblocked`.

------
#### [ Console ]

**To disable block public access for AMIs in the specified Region**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. From the navigation bar (at the top of the screen), select the Region in which to disable block public access for AMIs.

1. In the navigation pane, choose **Dashboard**.

1. On the **Account attributes** card, under **Settings**, choose **Data protection and security**.

1. Under **Block public access for AMIs**, choose **Manage**.

1. Clear the **Block new public sharing** checkbox, and then choose **Update**.

1. Enter **confirm** when prompted for confirmation, and then choose **Allow public sharing**.

------
#### [ AWS CLI ]

**To disable block public access for AMIs**  
Use the [disable-image-block-public-access](https://docs.aws.amazon.com/cli/latest/reference/ec2/disable-image-block-public-access.html) command.

**Example: For a specific Region**

```
aws ec2 disable-image-block-public-access --region us-east-1
```

The following is example output.

```
{
   "ImageBlockPublicAccessState": "unblocked"
}
```

**Example: For all Regions in your account**

```
echo -e "Region   \t Public Access State" ; \
echo -e "-------------- \t ----------------------" ; \
for region in $(
    aws ec2 describe-regions \
        --region us-east-1 \
        --query "Regions[*].[RegionName]" \
        --output text
    ); 
    do (output=$(
        aws ec2 disable-image-block-public-access \
            --region $region \
            --output text)
        echo -e "$region \t $output" 
    );
done
```

The following is example output.

```
Region           Public Access State
--------------   ----------------------
ap-south-1       unblocked
eu-north-1       unblocked
eu-west-3        unblocked
...
```

------
#### [ PowerShell ]

**To disable block public access for AMIs**  
Use the [Disable-EC2ImageBlockPublicAccess](https://docs.aws.amazon.com/powershell/latest/reference/items/Disable-EC2ImageBlockPublicAccess.html) cmdlet.

**Example: For a specific Region**

```
Disable-EC2ImageBlockPublicAccess -Region us-east-1
```

The following is example output.

```
Value
-----
unblocked
```

**Example: For all Regions in your account**

```
(Get-EC2Region).RegionName | `
    ForEach-Object {
    [PSCustomObject]@{
        Region            = $_
        PublicAccessState = (Disable-EC2ImageBlockPublicAccess -Region $_)
    }
} | `
Format-Table -AutoSize
```

The following is example output.

```
Region         PublicAccessState
------         -----------------
ap-south-1     unblocked
eu-north-1     unblocked
eu-west-3      unblocked
...
```

------

# Share an AMI with organizations and organizational units


 [AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_integrate_services_list.html) is an account management service that enables you to consolidate multiple AWS accounts into an organization that you create and centrally manage. You can share an AMI with an organization or an organizational unit (OU) that you have created, in addition to [sharing it with specific accounts](sharingamis-explicit.md).

An organization is an entity that you create to consolidate and centrally manage your AWS accounts. You can organize the accounts in a hierarchical, tree-like structure, with a [root](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_getting-started_concepts.html#root) at the top and [organizational units](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_getting-started_concepts.html#organizationalunit) nested under the organization root. Each account can be added directly to the root, or placed in one of the OUs in the hierarchy. For more information, see [AWS Organizations terminology and concepts](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_getting-started_concepts.html) in the *AWS Organizations User Guide*.

When you share an AMI with an organization or an OU, all of the children accounts gain access to the AMI. For example, in the following diagram, the AMI is shared with a top-level OU (indicated by the arrow at the number **1**). All of the OUs and accounts that are nested underneath that top-level OU (indicated by the dotted line at number **2**) also have access to the AMI. The accounts in the organization and OU outside the dotted line (indicated by the number **3**) do not have access to the AMI because they are not children of the OU that the AMI is shared with.

![\[The AMI is shared with an OU, and all children OUs and accounts get access to the AMI.\]](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/images/ami-share-with-orgs-and-ous.png)


**Topics**
+ [

## Considerations
](#considerations-org-ou)
+ [

# Get the ARN of an organization or organizational unit
](get-org-ou-ARN.md)
+ [

# Allow organizations and OUs to use a KMS key
](allow-org-ou-to-use-key.md)
+ [

# Manage AMI sharing with an organization or OU
](share-amis-org-ou-manage.md)

## Considerations


Consider the following when sharing AMIs with specific organizations or organizational units.
+ **Ownership** – To share an AMI, your AWS account must own the AMI.
+ **Sharing limits** – The AMI owner can share an AMI with any organization or OU, including organizations and OUs that they’re not a member of.

  For the maximum number of entities to which an AMI can be shared within a Region, see the [Amazon EC2 service quotas](https://docs.aws.amazon.com//general/latest/gr/ec2-service.html#limits_ec2).
+ **Tags** – You can't share user-defined tags (tags that you attach to an AMI). When you share an AMI, your user-defined tags are not available to any AWS account in an organization or OU with which the AMI is shared.
+ **ARN format** – When you specify an organization or OU in a command, make sure to use the correct ARN format. You'll get an error if you specify only the ID, for example, if you specify only `o-123example` or `ou-1234-5example`.

  Correct ARN formats:
  + Organization ARN: `arn:aws:organizations::111122223333:organization/organization-id`
  + OU ARN: `arn:aws:organizations::111122223333:ou/organization-id/ou-id`

  Where:
  + *`111122223333`* is an example of the 12-digit account ID for the management account. If you don't know the management account number, you can describe the organization or the organizational unit to get the ARN, which includes the management account number. For more information, see [Get the ARN of an organization or organizational unit](get-org-ou-ARN.md).
  + *`organization-id`* is the organization ID, for example, `o-123example`.
  + *`ou-id`* is the organizational unit ID, for example, `ou-1234-5example`.

  For more information about the format of ARNs, see [Amazon Resource Names (ARNs)](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html) in the *IAM User Guide*.
+ **Encryption and keys** – You can share AMIs that are backed by unencrypted and encrypted snapshots.
  + The encrypted snapshots must be encrypted with a customer managed key. You can’t share AMIs that are backed by snapshots that are encrypted with the default AWS managed key.
  + If you share an AMI that is backed by encrypted snapshots, you must allow the organizations or OUs to use the customer managed keys that were used to encrypt the snapshots. For more information, see [Allow organizations and OUs to use a KMS key](allow-org-ou-to-use-key.md).
+ **Region** – AMIs are a Regional resource. When you share an AMI, it is available only in the Region from which you shared it. To make an AMI available in a different Region, copy the AMI to the Region and then share it. For more information, see [Copy an Amazon EC2 AMI](CopyingAMIs.md).
+ **Usage** – When you share an AMI, users can only launch instances from the AMI. They can’t delete, share, or modify it. However, after they have launched an instance using your AMI, they can then create an AMI from the instance they launched.
+ **Billing** – You are not billed when your AMI is used by other AWS accounts to launch instances. The accounts that launch instances using the AMI are billed for the instances that they launch.

# Get the ARN of an organization or organizational unit


The organization and the organizational unit ARNs contain the 12-digit management account number. If you don't know the management account number, you can describe the organization and the organizational unit to get the ARN for each. In the following examples, `123456789012` is the account ID of the management account.

**Required permissions**  
Before you can get the ARNs, you must have the permission to describe organizations and organizational units. The following policy provides the necessary permission.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "organizations:Describe*"
            ],
            "Resource": "*"
        }
    ]
}
```

------

------
#### [ AWS CLI ]

**To get the ARN of an organization**  
Use the [https://docs.aws.amazon.com/cli/latest/reference/organizations/describe-organization.html](https://docs.aws.amazon.com/cli/latest/reference/organizations/describe-organization.html) command. Add the `--query` option to return only the organization ARN.

```
aws organizations describe-organization --query 'Organization.Arn'
```

The following is example output.

```
"arn:aws:organizations::123456789012:organization/o-1234567abc"
```

**To get the ARN of an organizational unit**  
Use the [https://docs.aws.amazon.com/cli/latest/reference/organizations/describe-organizational-unit.html](https://docs.aws.amazon.com/cli/latest/reference/organizations/describe-organizational-unit.html) command. Use the `--query` parameter to return only the organizational unit ARN.

```
aws organizations describe-organizational-unit \
    --organizational-unit-id ou-a123-b4567890 \
    --query 'OrganizationalUnit.Arn'
```

The following is example output.

```
"arn:aws:organizations::123456789012:ou/o-1234567abc/ou-a123-b4567890"
```

------
#### [ PowerShell ]

**To get the ARN of an organization**  
Use the [Get-ORGOrganization](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-ORGOrganization.html) cmdlet.

```
(Get-ORGOrganization).Arn
```

The following is example output.

```
arn:aws:organizations::123456789012:organization/o-1234567abc
```

**To get the ARN of an organizational unit**  
Use the [Get-ORGOrganizationalUnit](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-ORGOrganizationalUnit.html) cmdlet.

```
(Get-ORGOrganizationalUnit -OrganizationalUnitId "ou-a123-b4567890").Arn
```

The following is example output.

```
arn:aws:organizations::123456789012:ou/o-1234567abc/ou-a123-b4567890
```

------

# Allow organizations and OUs to use a KMS key


If you share an AMI that is backed by encrypted snapshots, you must also allow the organizations or organizational units (OUs) to use the KMS keys that were used to encrypt the snapshots.

**Note**  
The encrypted snapshots must be encrypted with a *customer managed* key. You can’t share AMIs that are backed by snapshots that are encrypted with the default AWS managed key.

To control access to the KMS key, in the [key policy](https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html) you can use the [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principalorgid](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principalorgid) and [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principalorgpaths](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principalorgpaths) condition keys to allow only specific principals permission to the specified actions. A principal can be a user, IAM role, federated user, or AWS account root user.

The condition keys are used as follows:
+ `aws:PrincipalOrgID` – Allows any principal belonging to the organization represented by the specified ID.
+ `aws:PrincipalOrgPaths` – Allows any principal belonging to the OUs represented by the specified paths.

To give an organization (including the OUs and accounts that belong to it) permission to use a KMS key, add the following statement to the key policy.

```
{
    "Sid": "Allow access for organization root",
    "Effect": "Allow",
    "Principal": "*",
    "Action": [
        "kms:Describe*",
        "kms:List*",
        "kms:Get*",
        "kms:Encrypt",
        "kms:Decrypt",
        "kms:ReEncrypt*",
        "kms:GenerateDataKey*",
        "kms:CreateGrant"
    ],
    "Resource": "*",
    "Condition": {
        "StringEquals": {
            "aws:PrincipalOrgID": "o-123example"
        }
    }
}
```

To give specific OUs (and the accounts that belong to it) permission to use a KMS key, you can use a policy similar to the following example.

```
{
        "Sid": "Allow access for specific OUs and their descendants",
        "Effect": "Allow",
        "Principal": "*",
        "Action": [
            "kms:Describe*",
            "kms:List*",
            "kms:Get*",
            "kms:Encrypt",
            "kms:Decrypt",
            "kms:ReEncrypt*",
            "kms:GenerateDataKey*",
            "kms:CreateGrant"
        ],
        "Resource": "*",
        "Condition": {
            "StringEquals": {
                "aws:PrincipalOrgID": "o-123example"
            },
            "ForAnyValue:StringLike": {
                "aws:PrincipalOrgPaths": [
                    "o-123example/r-ab12/ou-ab12-33333333/*",
                    "o-123example/r-ab12/ou-ab12-22222222/*"
                ]
            }
        }
}
```

For more example condition statements, see [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principalorgid](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principalorgid) and [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principalorgpaths](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principalorgpaths) in the *IAM User Guide*. 

For information about cross-account access, see [Allowing users in other accounts to use a KMS key](https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-modifying-external-accounts.html) in the *AWS Key Management Service Developer Guide*.

# Manage AMI sharing with an organization or OU


You can manage AMI sharing with organizations and organization units (OU) to control whether they can launch Amazon EC2 instances.

## View the organizations and OUs with which an AMI is shared
View organizations and OUs an AMI is shared with

You can find the organizations and OUs with which you've shared your AMI.

------
#### [ Console ]

**To check with which organizations and OUs you've shared your AMI**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **AMIs**.

1. Select your AMI in the list, choose the **Permissions** tab, and scroll down to **Shared organizations/OUs**.

   To find AMIs that are shared with you, see [Find shared AMIs to use for Amazon EC2 instances](usingsharedamis-finding.md).

------
#### [ AWS CLI ]

**To check with which organizations and OUs you've shared your AMI**  
Use the [https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-image-attribute.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-image-attribute.html) command with the `launchPermission` attribute.

```
aws ec2 describe-image-attribute \
    --image-id ami-0abcdef1234567890 \
    --attribute launchPermission
```

The following is an example response.

```
{
    "ImageId": "ami-0abcdef1234567890",
    "LaunchPermissions": [
        {
            "OrganizationalUnitArn": "arn:aws:organizations::111122223333:ou/o-123example/ou-1234-5example"
        }
    ]
}
```

------
#### [ PowerShell ]

**To check with which organizations and OUs you've shared your AMI**  
Use the [Get-EC2ImageAttribute](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2ImageAttribute.html) cmdlet.

```
Get-EC2ImageAttribute `
    -ImageId ami-0abcdef1234567890 `
    -Attribute launchPermission
```

------

## Share an AMI with an organization or OU


You can share an AMI with an organization or OU.

**Note**  
You do not need to share the Amazon EBS snapshots that an AMI references in order to share the AMI. Only the AMI itself needs to be shared, and the system automatically provides the instance with access to the referenced EBS snapshots for the launch. However, you do need to share the KMS keys used to encrypt snapshots that the AMI references. For more information, see [Allow organizations and OUs to use a KMS key](allow-org-ou-to-use-key.md).

------
#### [ Console ]

**To share an AMI with an organization or an OU**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **AMIs**.

1. Select your AMI in the list, and then choose **Actions**, **Edit AMI permissions**.

1. Under **AMI availability**, choose **Private**.

1. Next to **Shared organizations/OUs**, choose **Add organization/OU ARN**.

1. For **Organization/OU ARN**, enter the organization ARN or OU ARN with which you want to share the AMI, and then choose **Share AMI**. Note that you must specify the full ARN, not just the ID.

   To share this AMI with multiple organizations or OUs, repeat this step until you have added all of the required organizations or OUs.

1. Choose **Save changes** when you're done.

1. (Optional) To view the organizations or OUs with which you have shared the AMI, select the AMI in the list, choose the **Permissions** tab, and scroll down to **Shared organizations/OUs**. To find AMIs that are shared with you, see [Find shared AMIs to use for Amazon EC2 instances](usingsharedamis-finding.md).

------
#### [ AWS CLI ]

**To share an AMI with an organization**  
Use the [https://docs.aws.amazon.com/cli/latest/reference/ec2/modify-image-attribute.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/modify-image-attribute.html) command to grant launch permissions for the specified AMI to the specified organization.

```
aws ec2 modify-image-attribute \
    --image-id ami-0abcdef1234567890 \
    --launch-permission "Add=[{OrganizationArn=arn:aws:organizations::123456789012:organization/o-123example}]"
```

**To share an AMI with an OU**  
The [modify-image-attribute](https://docs.aws.amazon.com/cli/latest/reference/ec2/modify-image-attribute.html) command grants launch permissions for the specified AMI to the specified OU. Note that you must specify the full ARN, not just the ID.

```
aws ec2 modify-image-attribute \
    --image-id ami-0abcdef1234567890 \
    --launch-permission "Add=[{OrganizationalUnitArn=arn:aws:organizations::123456789012:ou/o-123example/ou-1234-5example}]"
```

------
#### [ PowerShell ]

Use the [https://docs.aws.amazon.com/powershell/latest/reference/items/Edit-EC2ImageAttribute.html](https://docs.aws.amazon.com/powershell/latest/reference/items/Edit-EC2ImageAttribute.html) command (Tools for Windows PowerShell) to share an AMI as shown in the following examples.

**To share an AMI with an organization or an OU**  
The following command grants launch permissions for the specified AMI to the specified organization.

```
Edit-EC2ImageAttribute `
    -ImageId ami-0abcdef1234567890 `
    -Attribute launchPermission `
    -OperationType add `
    -OrganizationArn "arn:aws:organizations::123456789012:organization/o-123example"
```

**To stop sharing an AMI with an organization or OU**  
The following command removes launch permissions for the specified AMI from the specified organization:

```
Edit-EC2ImageAttribute `
    -ImageId ami-0abcdef1234567890 `
    -Attribute launchPermission `
    -OperationType remove `
    -OrganizationArn "arn:aws:organizations::123456789012:organization/o-123example"
```

**To stop sharing an AMI with all organizations, OUs, and AWS accounts**  
The following command removes all public and explicit launch permissions from the specified AMI. Note that the owner of the AMI always has launch permissions and is therefore unaffected by this command.

```
Reset-EC2ImageAttribute `
    -ImageId ami-0abcdef1234567890 `
    -Attribute launchPermission
```

------

## Stop sharing an AMI with an organization or OU


You can stop sharing an AMI with an organization or OU.

**Note**  
You can't stop sharing an AMI with a specific account if it's in an organization or OU with which an AMI is shared. If you try to stop sharing the AMI by removing launch permissions for the account, Amazon EC2 returns a success message. However, the AMI continues to be shared with the account.

------
#### [ Console ]

**To stop sharing an AMI with an organization or OU**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **AMIs**.

1. Select your AMI in the list, and then choose **Actions**, **Edit AMI permissions**.

1. Under **Shared organizations/OUs**, select the organizations or OUs with which you want to stop sharing the AMI, and then choose **Remove selected**.

1. Choose **Save changes** when you're done.

1. (Optional) To confirm that you have stopped sharing the AMI with the organizations or OUs, select the AMI in the list, choose the **Permissions** tab, and scroll down to **Shared organizations/OUs**.

------
#### [ AWS CLI ]

**To stop sharing an AMI with an organization or OU**  
Use the [modify-image-attribute](https://docs.aws.amazon.com/cli/latest/reference/ec2/modify-image-attribute.html) command. This example removes launch permissions for the specified AMI from the specified organization.

```
aws ec2 modify-image-attribute \
    --image-id ami-0abcdef1234567890 \
    --launch-permission "Remove=[{OrganizationArn=arn:aws:organizations::123456789012:organization/o-123example}]"
```

**To stop sharing an AMI with all organizations, OUs, and AWS accounts**  
Use the [https://docs.aws.amazon.com/cli/latest/reference/ec2/reset-image-attribute.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/reset-image-attribute.html) command. This example removes all public and explicit launch permissions from the specified AMI. Note that the owner of the AMI always has launch permissions and is therefore unaffected by this command.

```
aws ec2 reset-image-attribute \
    --image-id ami-0abcdef1234567890 \
    --attribute launchPermission
```

------
#### [ PowerShell ]

**To stop sharing an AMI with an organization or OU**  
Use the [Edit-EC2ImageAttribute](https://docs.aws.amazon.com/powershell/latest/reference/items/Edit-EC2ImageAttribute.html) cmdlet. This example removes launch permissions for the specified AMI from the specified organization.

```
Edit-EC2ImageAttribute `
    -ImageId ami-0abcdef1234567890 `
    -Attribute launchPermission `
    -OperationType remove `
    -OrganizationArn "arn:aws:organizations::123456789012:organization/o-123example"
```

**To stop sharing an AMI with all organizations, OUs, and AWS accounts**  
Use the [Reset-EC2ImageAttribute](https://docs.aws.amazon.com/powershell/latest/reference/items/Reset-EC2ImageAttribute.html) cmdlet. This example removes all public and explicit launch permissions from the specified AMI. Note that the owner of the AMI always has launch permissions and is therefore unaffected by this command.

```
Reset-EC2ImageAttribute `
    -ImageId ami-0abcdef1234567890 `
    -Attribute LaunchPermission
```

------

# Share an AMI with specific AWS accounts


You can share an AMI with specific AWS accounts without making the AMI public. All you need are the AWS account IDs.

An AWS account ID is a 12-digit number, such as `012345678901`, that uniquely identifies an AWS account. For more information, see [View AWS account identifiers](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-identifiers.html) in the *AWS Account Management Reference Guide*.



## Considerations


Consider the following when sharing AMIs with specific AWS accounts.
+ **Ownership** – To share an AMI, your AWS account must own the AMI.
+ **Sharing limits** – For the maximum number of entities to which an AMI can be shared within a Region, see the [Amazon EC2 service quotas](https://docs.aws.amazon.com//general/latest/gr/ec2-service.html#limits_ec2).
+ **Tags** – You can't share user-defined tags (tags that you attach to an AMI). When you share an AMI, your user-defined tags are not available to any AWS account that the AMI is shared with.
+ **Snapshots** – You do not need to share the Amazon EBS snapshots that an AMI references in order to share the AMI. You can share only the AMI itself; the system provides the instance access to the referenced EBS snapshots for the launch. However, you must share any KMS keys used to encrypt snapshots that an AMI references. For more information, see [Share an Amazon EBS snapshot](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-modifying-snapshot-permissions.html) in the *Amazon EBS User Guide*.
+ **Encryption and keys** – You can share AMIs that are backed by unencrypted and encrypted snapshots.
  + The encrypted snapshots must be encrypted with a KMS key. You can’t share AMIs that are backed by snapshots that are encrypted with the default AWS managed key.
  + If you share an AMI that is backed by encrypted snapshots, you must allow the AWS accounts to use the KMS keys that were used to encrypt the snapshots. For more information, see [Allow organizations and OUs to use a KMS key](allow-org-ou-to-use-key.md). To set up the key policy that you need to launch Auto Scaling instances when you use a customer managed key for encryption, see [Required AWS KMS key policy for use with encrypted volumes](https://docs.aws.amazon.com/autoscaling/ec2/userguide/key-policy-requirements-EBS-encryption.html) in the *Amazon EC2 Auto Scaling User Guide*. 
+ **Region** – AMIs are a Regional resource. When you share an AMI, it is only available in that Region. To make an AMI available in a different Region, copy the AMI to the Region and then share it. For more information, see [Copy an Amazon EC2 AMI](CopyingAMIs.md).
+ **Usage** – When you share an AMI, users can only launch instances from the AMI. They can’t delete, share, or modify it. However, after they have launched an instance using your AMI, they can then create an AMI from their instance.
+ **Copying shared AMIs** – If users in another account want to copy a shared AMI, you must grant them read permissions for the storage that backs the AMI. For more information, see [Cross-account copying](how-ami-copy-works.md#copy-ami-across-accounts).
+ **Billing** – You are not billed when your AMI is used by other AWS accounts to launch instances. The accounts that launch instances using the AMI are billed for the instances that they launch.

------
#### [ Console ]

**To grant explicit launch permissions**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **AMIs**.

1. Select your AMI in the list, and then choose **Actions**, **Edit AMI permissions**.

1. Choose **Private**.

1. Under **Shared accounts**, choose **Add account ID**.

1. For **AWS account ID**, enter the AWS account ID with which you want to share the AMI, and then choose **Share AMI**.

   To share this AMI with multiple accounts, repeat Steps 5 and 6 until you have added all the required account IDs.

1. Choose **Save changes** when you are done.

1. (Optional) To view the AWS account IDs with which you have shared the AMI, select the AMI in the list, and choose the **Permissions** tab. To find AMIs that are shared with you, see [Find shared AMIs to use for Amazon EC2 instances](usingsharedamis-finding.md).

------
#### [ AWS CLI ]

Use the [https://docs.aws.amazon.com/cli/latest/reference/ec2/modify-image-attribute.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/modify-image-attribute.html) command to share an AMI as shown in the following examples.

**To grant explicit launch permissions**  
The following example grants launch permissions for the specified AMI to the specified AWS account.

```
aws ec2 modify-image-attribute \
    --image-id ami-0abcdef1234567890 \
    --launch-permission "Add=[{UserId=123456789012}]"
```

**To remove launch permissions for an account**  
The following example removes launch permissions for the specified AMI from the specified AWS account.

```
aws ec2 modify-image-attribute \
    --image-id ami-0abcdef1234567890 \
    --launch-permission "Remove=[{UserId=123456789012}]"
```

**To remove all launch permissions**  
The following example removes all public and explicit launch permissions from the specified AMI. Note that the owner of the AMI always has launch permissions and is therefore unaffected by this command.

```
aws ec2 reset-image-attribute \
    --image-id ami-0abcdef1234567890 \
    --attribute launchPermission
```

------
#### [ PowerShell ]

Use the [https://docs.aws.amazon.com/powershell/latest/reference/items/Edit-EC2ImageAttribute.html](https://docs.aws.amazon.com/powershell/latest/reference/items/Edit-EC2ImageAttribute.html) command (Tools for Windows PowerShell) to share an AMI as shown in the following examples.

**To grant explicit launch permissions**  
The following example grants launch permissions for the specified AMI to the specified AWS account.

```
Edit-EC2ImageAttribute `
    -ImageId ami-0abcdef1234567890 ` 
    -Attribute launchPermission `
    -OperationType add `
    -UserId "123456789012"
```

**To remove launch permissions for an account**  
The following example removes launch permissions for the specified AMI from the specified AWS account.

```
Edit-EC2ImageAttribute `
    -ImageId ami-0abcdef1234567890 `
    -Attribute launchPermission -OperationType remove `
    -UserId "123456789012"
```

**To remove all launch permissions**  
The following exaple removes all public and explicit launch permissions from the specified AMI. Note that the owner of the AMI always has launch permissions and is therefore unaffected by this command.

```
Reset-EC2ImageAttribute `
    -ImageId ami-0abcdef1234567890 `
    -Attribute launchPermission
```

------

# Cancel having an AMI shared with your AWS account
Cancel having an AMI shared with your account

An Amazon Machine Image (AMI) can be [shared with specific AWS accounts](sharingamis-explicit.md) by adding the accounts to the AMI's launch permissions. If an AMI has been shared with your AWS account and you no longer want it shared with your account, you can remove your account from the AMI's launch permissions. You do this by running the `cancel-image-launch-permission` AWS CLI command. When running this command, your AWS account is removed from the launch permissions for the specified AMI. To find the AMIs that are shared with your AWS account, see [Find shared AMIs to use for Amazon EC2 instances](usingsharedamis-finding.md).

You might cancel having an AMI shared with your account, for example, to reduce the likelihood of launching an instance with an unused or deprecated AMI that was shared with you. When you cancel having an AMI shared with your account, it no longer appears in any AMI lists in the EC2 console or in the output for [describe-images](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html).

**Topics**
+ [

## Limitations
](#cancel-sharing-an-AMI-limitations)
+ [

## Cancel having an AMI shared with your account
](#cancel-image-launch-permission)

## Limitations

+ You can remove your account from the launch permissions of an AMI that is shared with your AWS account only. You can't use `cancel-image-launch-permission` to remove your account from the launch permissions of an [AMI shared with an organization or organizational unit (OU)](share-amis-with-organizations-and-OUs.md) or to remove access to public AMIs.
+ You can’t permanently remove your account from the launch permissions of an AMI. An AMI owner can share an AMI with your account again.
+ AMIs are a Regional resource. When running `cancel-image-launch-permission`, you must specify the Region in which the AMI is located. Either specify the Region in the command, or use the AWS\$1DEFAULT\$1REGION [environment variable](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html).
+ Only the AWS CLI and SDKs support removing your account from the launch permissions of an AMI. The EC2 console does not currently support this action.

## Cancel having an AMI shared with your account


**Note**  
After you cancel having an AMI shared with your account, you can't undo it. To regain access to the AMI, the AMI owner must share it with your account.

------
#### [ AWS CLI ]

**To cancel having an AMI shared with your account**  
Use the [https://docs.aws.amazon.com/cli/latest/reference/ec2/cancel-image-launch-permission.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/cancel-image-launch-permission.html) command.

```
aws ec2 cancel-image-launch-permission \
    --image-id ami-0abcdef1234567890 \
    --region us-east-1
```

------
#### [ PowerShell ]

**To cancel having an AMI shared with your account**  
Use the [https://docs.aws.amazon.com/powershell/latest/reference/index.html](https://docs.aws.amazon.com/powershell/latest/reference/index.html) cmdlet.

```
Stop-EC2ImageLaunchPermission `
    -ImageId ami-0abcdef1234567890 `
    -Region us-east-1
```

------

# Recommendations for creating shared Linux AMIs


Use the following guidelines to reduce the attack surface and improve the reliability of the AMIs you create.

**Important**  
No list of security guidelines can be exhaustive. Build your shared AMIs carefully and take time to consider where you might expose sensitive data.

**Topics**
+ [

## Disable password-based remote logins for the root user
](#public-amis-disable-password-logins-for-root)
+ [

## Disable local root access
](#restrict-root-access)
+ [

## Remove SSH host key pairs
](#remove-ssh-host-key-pairs)
+ [

## Install public key credentials
](#public-amis-install-credentials)
+ [

## Disable sshd DNS checks (optional)
](#public-amis-disable-ssh-dns-lookups)
+ [

## Remove sensitive data
](#public-amis-protect-yourself)

If you are building AMIs for AWS Marketplace, see [Best practices for building AMIs](https://docs.aws.amazon.com/marketplace/latest/userguide/best-practices-for-building-your-amis.html) in the *AWS Marketplace Seller Guide* for guidelines, policies, and best practices.

## Disable password-based remote logins for the root user


Using a fixed root password for a public AMI is a security risk that can quickly become known. Even relying on users to change the password after the first login opens a small window of opportunity for potential abuse. 

To solve this problem, disable password-based remote logins for the root user.

**To disable password-based remote logins for the root user**

1. Open the `/etc/ssh/sshd_config` file with a text editor and locate the following line:

   ```
   #PermitRootLogin yes
   ```

1. Change the line to:

   ```
   PermitRootLogin without-password
   ```

   The location of this configuration file might differ for your distribution, or if you are not running OpenSSH. If this is the case, consult the relevant documentation. 

## Disable local root access


When you work with shared AMIs, a best practice is to disable direct root logins. To do this, log into your running instance and issue the following command:

```
[ec2-user ~]$ sudo passwd -l root
```

**Note**  
This command does not impact the use of `sudo`.

## Remove SSH host key pairs


 If you plan to share an AMI derived from a public AMI, remove the existing SSH host key pairs located in `/etc/ssh`. This forces SSH to generate new unique SSH key pairs when someone launches an instance using your AMI, improving security and reducing the likelihood of "man-in-the-middle" attacks. 

Remove all of the following key files that are present on your system.
+  ssh\$1host\$1dsa\$1key 
+  ssh\$1host\$1dsa\$1key.pub 
+  ssh\$1host\$1key 
+  ssh\$1host\$1key.pub 
+  ssh\$1host\$1rsa\$1key 
+  ssh\$1host\$1rsa\$1key.pub 
+ ssh\$1host\$1ecdsa\$1key
+ ssh\$1host\$1ecdsa\$1key.pub
+ ssh\$1host\$1ed25519\$1key
+ ssh\$1host\$1ed25519\$1key.pub

You can securely remove all of these files with the following command.

```
[ec2-user ~]$ sudo shred -u /etc/ssh/*_key /etc/ssh/*_key.pub
```

**Warning**  
Secure deletion utilities such as **shred** might not remove all copies of a file from your storage media. Hidden copies of files may be created by journalling file systems (including Amazon Linux default ext4), snapshots, backups, RAID, and temporary caching. For more information, see the [shred documentation](https://www.gnu.org/software/coreutils/manual/html_node/shred-invocation.html).

**Important**  
If you forget to remove the existing SSH host key pairs from your public AMI, our routine auditing process notifies you and all customers running instances of your AMI of the potential security risk. After a short grace period, we mark the AMI private. 

## Install public key credentials


After configuring the AMI to prevent logging in using a password, you must make sure users can log in using another mechanism. 

Amazon EC2 allows users to specify a public-private key pair name when launching an instance. When a valid key pair name is provided to the `RunInstances` API call (or through the command line API tools), the public key (the portion of the key pair that Amazon EC2 retains on the server after a call to `CreateKeyPair` or `ImportKeyPair`) is made available to the instance through an HTTP query against the instance metadata. 

To log in through SSH, your AMI must retrieve the key value at boot and append it to `/root/.ssh/authorized_keys` (or the equivalent for any other user account on the AMI). Users can launch instances of your AMI with a key pair and log in without requiring a root password. 

Many distributions, including Amazon Linux and Ubuntu, use the `cloud-init` package to inject public key credentials for a configured user. If your distribution does not support `cloud-init`, you can add the following code to a system start-up script (such as `/etc/rc.local`) to pull in the public key you specified at launch for the root user.

**Note**  
In the following example, the IP address http://169.254.169.254/ is a link-local address and is valid only from the instance.

------
#### [ IMDSv2 ]

```
if [ ! -d /root/.ssh ] ; then
        mkdir -p /root/.ssh
        chmod 700 /root/.ssh
fi
# Fetch public key using HTTP
TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` \
&& curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key > /tmp/my-key
if [ $? -eq 0 ] ; then
        cat /tmp/my-key >> /root/.ssh/authorized_keys
        chmod 700 /root/.ssh/authorized_keys
        rm /tmp/my-key
fi
```

------
#### [ IMDSv1 ]

```
if [ ! -d /root/.ssh ] ; then
        mkdir -p /root/.ssh
        chmod 700 /root/.ssh
fi
# Fetch public key using HTTP
curl http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key > /tmp/my-key
if [ $? -eq 0 ] ; then
        cat /tmp/my-key >> /root/.ssh/authorized_keys
        chmod 700 /root/.ssh/authorized_keys
        rm /tmp/my-key
fi
```

------

 This can be applied to any user; you do not need to restrict it to the `root` user.

**Note**  
Rebundling an instance based on this AMI includes the key with which it was launched. To prevent the key's inclusion, you must clear out (or delete) the `authorized_keys` file or exclude this file from rebundling. 

## Disable sshd DNS checks (optional)


Disabling sshd DNS checks slightly weakens your sshd security. However, if DNS resolution fails, SSH logins still work. If you do not disable sshd checks, DNS resolution failures prevent all logins. 

**To disable sshd DNS checks**

1. Open the `/etc/ssh/sshd_config` file with a text editor and locate the following line:

   ```
   #UseDNS yes
   ```

1. Change the line to: 

   ```
   UseDNS no
   ```

**Note**  
The location of this configuration file can differ for your distribution or if you are not running OpenSSH. If this is the case, consult the relevant documentation. 

## Remove sensitive data


We recommend against storing sensitive data or software on any AMI that you share. Users who launch a shared AMI might be able to rebundle it and register it as their own. Follow these guidelines to help you to avoid some easily overlooked security risks: 
+ We recommend using the `--exclude directory` option on `ec2-bundle-vol` to skip any directories and subdirectories that contain secret information that you would not like to include in your bundle. In particular, exclude all user-owned SSH public/private key pairs and SSH `authorized_keys` files when bundling the image. The Amazon public AMIs store these in `/root/.ssh` for the root user, and `/home/user_name/.ssh/` for regular users. For more information, see [ec2-bundle-vol](ami-tools-commands.md#ami-bundle-vol).
+ Always delete the shell history before bundling. If you attempt more than one bundle upload in the same AMI, the shell history contains your access key. The following example should be the last command you run before bundling from within the instance.

  ```
  [ec2-user ~]$ shred -u ~/.*history
  ```
**Warning**  
The limitations of **shred** described in the warning above apply here as well.   
Be aware that bash writes the history of the current session to the disk on exit. If you log out of your instance after deleting `~/.bash_history`, and then log back in, you will find that `~/.bash_history` has been re-created and contains all of the commands you ran during your previous session.  
Other programs besides bash also write histories to disk, Use caution and remove or exclude unnecessary dot-files and dot-directories.
+ Bundling a running instance requires your private key and X.509 certificate. Put these and other credentials in a location that is not bundled (such as the instance store).

# Monitor AMI events using Amazon EventBridge
Monitor AMI events

When the state of an Amazon Machine Image (AMI) changes, Amazon EC2 generates an event that is sent to Amazon EventBridge (formerly known as Amazon CloudWatch Events). The events are sent to the default EventBridge event bus in JSON format. You can use Amazon EventBridge to detect and react to these events. You do this by creating rules in EventBridge that trigger an action in response to an event. For example, you can create an EventBridge rule that detects when the AMI creation process has completed and then invokes an Amazon SNS topic to send an email notification to you.

Amazon EC2 generates an `EC2 AMI State Change` event when an AMI enters any of the following states:
+ `available`
+ `failed`
+ `deregistered`
+ `disabled`

Events are generated on a best effort basis.

The following table lists the AMI operations and the states that an AMI can enter. In the table, **Yes** indicates the states that the AMI can enter when the corresponding operation runs.


| AMI operations | available | failed | deregistered | disabled | 
| --- | --- | --- | --- | --- | 
| CopyImage | Yes | Yes |  |  | 
|  CreateImage  |  Yes  |  Yes  |  |  | 
|  CreateRestoreImageTask  | Yes | Yes |  |  | 
| DeregisterImage |  |  |  Yes  |  | 
|  DisableImage  |  |  |  |  Yes  | 
|  EnableImage  |  Yes  |  |  |  | 
| RegisterImage | Yes | Yes |  |  | 

**EC2 AMI State Change events**
+ [

## Event details
](#ami-events)
+ [

## available events
](#ami-event-available)
+ [

## failed events
](#ami-event-failed)
+ [

## deregistered events
](#ami-event-deregistered)
+ [

## disabled events
](#ami-event-disabled)

## Event details


You can use the following fields in the event to create rules that trigger an action:

`"source": "aws.ec2"`  
Identifies that the event is from Amazon EC2.

`"detail-type": "EC2 AMI State Change"`  
Identifies the event name.

`"detail": { "ImageId": "ami-0abcdef1234567890", "State": "available", }`  
Provides the AMI ID and the state of the AMI (`available`, `failed`, `deregistered`, or `disabled`).

For more information, see the following in the *Amazon EventBridge User Guide*:
+ [Amazon EventBridge events](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-events.html)
+ [Amazon EventBridge event patterns](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-event-patterns.html)
+ [Amazon EventBridge rules](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-rules.html)

For a tutorial about how to create a Lambda function and an EventBridge rule that runs the Lambda function, see [Tutorial: Log the state of an Amazon EC2 instance using EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-log-ec2-instance-state.html) in the *AWS Lambda Developer Guide*.

## available events


The following is an example of an event that Amazon EC2 generates when the AMI enters the `available` state following a successful `CreateImage`, `CopyImage`, `RegisterImage`, `CreateRestoreImageTask`, or `EnableImage` operation.

`"State": "available"` indicates that the operation was successful.

```
{
    "version": "0",
    "id": "example-9f07-51db-246b-d8b8441bcdf0",
    "detail-type": "EC2 AMI State Change",
    "source": "aws.ec2",
    "account": "012345678901",
    "time": "yyyy-mm-ddThh:mm:ssZ",
    "region": "us-east-1",
    "resources": ["arn:aws:ec2:us-east-1::image/ami-0abcdef1234567890"],
    "detail": {
        "RequestId": "example-9dcc-40a6-aa77-7ce457d5442b",
        "ImageId": "ami-0abcdef1234567890",
        "State": "available",
        "ErrorMessage": ""
    }
}
```

## failed events


The following is an example of an event that Amazon EC2 generates when the AMI enters the `failed` state following a failed `CreateImage`, `CopyImage`, `RegisterImage`, or `CreateRestoreImageTask` operation.

The following fields provide pertinent information:
+ `"State": "failed"` – Indicates that the operation failed.
+ `"ErrorMessage": ""` – Provides the reason for the failed operation.

```
{
    "version": "0",
    "id": "example-9f07-51db-246b-d8b8441bcdf0",
    "detail-type": "EC2 AMI State Change",
    "source": "aws.ec2",
    "account": "012345678901",
    "time": "yyyy-mm-ddThh:mm:ssZ",
    "region": "us-east-1",
    "resources": ["arn:aws:ec2:us-east-1::image/ami-0abcdef1234567890"],
    "detail": {
        "RequestId": "example-9dcc-40a6-aa77-7ce457d5442b",
        "ImageId": "ami-0abcdef1234567890",
        "State": "failed",
        "ErrorMessage": "Description of failure"
    }
}
```

## deregistered events


The following is an example of an event that Amazon EC2 generates when the AMI enters the `deregistered` state following a successful `DeregisterImage` operation. If the operation fails, no event is generated. Any failure is known immediately because `DeregisterImage` is a synchronous operation.

`"State": "deregistered"` indicates that the `DeregisterImage` operation was successful.

```
{
    "version": "0",
    "id": "example-9f07-51db-246b-d8b8441bcdf0",
    "detail-type": "EC2 AMI State Change",
    "source": "aws.ec2",
    "account": "012345678901",
    "time": "yyyy-mm-ddThh:mm:ssZ",
    "region": "us-east-1",
    "resources": ["arn:aws:ec2:us-east-1::image/ami-0abcdef1234567890"],
    "detail": {
        "RequestId": "example-9dcc-40a6-aa77-7ce457d5442b",
        "ImageId": "ami-0abcdef1234567890",
        "State": "deregistered",
        "ErrorMessage": ""
    }
}
```

## disabled events


The following is an example of an event that Amazon EC2 generates when the AMI enters the `disabled` state following a successful `DisableImage` operation. If the operation fails, no event is generated. Any failure is known immediately because `DisableImage` is a synchronous operation.

`"State": "disabled"` indicates that the `DisableImage` operation was successful.

```
{
    "version": "0",
    "id": "example-9f07-51db-246b-d8b8441bcdf0",
    "detail-type": "EC2 AMI State Change",
    "source": "aws.ec2",
    "account": "012345678901",
    "time": "yyyy-mm-ddThh:mm:ssZ",
    "region": "us-east-1",
    "resources": ["arn:aws:ec2:us-east-1::image/ami-0abcdef1234567890"],
    "detail": {
        "RequestId": "example-9dcc-40a6-aa77-7ce457d5442b",
        "ImageId": "ami-0abcdef1234567890",
        "State": "disabled",
        "ErrorMessage": ""
    }
}
```

# Understand AMI billing information
Understand AMI billing

There are many Amazon Machine Images (AMIs) to choose from when launching your instances, and they support a variety of operating system platforms and features. To understand how the AMI you choose when launching your instance affects the bottom line on your AWS bill, you can research the associated operating system platform and billing information. Do this before you launch any On-Demand or Spot Instances, or purchase a Reserved Instance.

Here are two examples of how researching your AMI in advance can help you choose the AMI that best suits your needs:
+ For Spot Instances, you can use the AMI **Platform details** to confirm that the AMI is supported for Spot Instances.
+ When purchasing a Reserved Instance, you can make sure that you select the operating system platform (**Platform**) that maps to the AMI **Platform details**.

For more information about instance pricing, see [Amazon EC2 pricing](https://aws.amazon.com/ec2/pricing/).

**Topics**
+ [

# AMI billing information fields
](billing-info-fields.md)
+ [

# Finding AMI billing and usage details
](view-billing-info.md)
+ [

# Verify AMI charges on your bill
](verify-ami-charges.md)

# AMI billing information fields
AMI billing fields

The following fields provide billing information associated with an AMI:

Platform details  
 The platform details associated with the billing code of the AMI. For example, `Red Hat Enterprise Linux`.

Usage operation  
The operation of the Amazon EC2 instance and the billing code that is associated with the AMI. For example, `RunInstances:0010`. **Usage operation** corresponds to the [lineitem/Operation](https://docs.aws.amazon.com/cur/latest/userguide/Lineitem-columns.html#Lineitem-details-O-Operation) column on your AWS Cost and Usage Report (CUR) and in the [AWS Price List API](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/price-changes.html).

You can view these fields on the **Instances** or **AMIs** page in the Amazon EC2 console, or in the response that is returned by the [describe-images](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) or [Get-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Image.html) command.

## Sample data: usage operation by platform


The following table lists some of the platform details and usage operation values that can be displayed on the **Instances** or **AMIs** pages in the Amazon EC2 console, or in the response that is returned by the [describe-images](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) or [Get-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Image.html) command.


| Platform details | Usage operation 2 | 
| --- | --- | 
|  Linux/UNIX  |  RunInstances  | 
|  Red Hat BYOL Linux  |  RunInstances:00g0 3  | 
|  Red Hat Enterprise Linux  |  RunInstances:0010  | 
|  Red Hat Enterprise Linux with HA  |  RunInstances:1010  | 
|  Red Hat Enterprise Linux with SQL Server Standard and HA  |  RunInstances:1014  | 
|  Red Hat Enterprise Linux with SQL Server Enterprise and HA  |  RunInstances:1110  | 
|  Red Hat Enterprise Linux with SQL Server Standard  |  RunInstances:0014  | 
|  Red Hat Enterprise Linux with SQL Server Web  |  RunInstances:0210  | 
|  Red Hat Enterprise Linux with SQL Server Enterprise  |  RunInstances:0110  | 
|  SQL Server Enterprise  |  RunInstances:0100  | 
|  SQL Server Standard  |  RunInstances:0004  | 
|  SQL Server Web  |  RunInstances:0200  | 
|  SUSE Linux  |  RunInstances:000g  | 
| Ubuntu Pro |  RunInstances:0g00  | 
|  Windows  |  RunInstances:0002  | 
|  Windows BYOL  |  RunInstances:0800  | 
|  Windows with SQL Server Enterprise 1  |  RunInstances:0102  | 
|  Windows with SQL Server Standard 1  |  RunInstances:0006  | 
|  Windows with SQL Server Web 1  |  RunInstances:0202  | 

1 If two software licenses are associated with an AMI, the **Platform details** field shows both.

2 If you are running Spot Instances, the [https://docs.aws.amazon.com/cur/latest/userguide/Lineitem-columns.html#Lineitem-details-O-Operation](https://docs.aws.amazon.com/cur/latest/userguide/Lineitem-columns.html#Lineitem-details-O-Operation) on your AWS Cost and Usage Report might be different from the **Usage operation** value that is listed here. For example, if `[lineitem/Operation](https://docs.aws.amazon.com/cur/latest/userguide/Lineitem-columns.html#Lineitem-details-O-Operation)` displays `RunInstances:0010:SV006`, it means that Amazon EC2 is running Red Hat Enterprise Linux Spot Instance-hour in US East (N. Virginia) in Zone 6.

3 This appears as RunInstances (Linux/UNIX) in your usage reports.

# Finding AMI billing and usage details
Find AMI billing information

The following properties can help you verify AMI charges on your bill:
+ **Platform details**
+ **Usage operation**
+ **AMI ID**

------
#### [ Console ]

**To find the AMI billing information for an AMI**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **AMIs**.

1. Select the AMI.

1. On the **Details** tab, find **Platform details** and **Usage operation**.

**To find the AMI billing information for an instance**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **Instances**.

1. Select the instance.

1. On the **Details** tab, expand **Instance details** and find **Platform details** and **Usage operation**.

------
#### [ AWS CLI ]

**To find the AMI billing information for an AMI**  
Use the [describe-images](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) command.

```
aws ec2 describe-images \
    --image-ids ami-0abcdef1234567890 \
    --query "Images[].{PlatformDetails:PlatformDetails,UsageOperation:UsageOperation}"
```

The following is example output for a Linux AMI.

```
[
    {
        "PlatformDetails": "Linux/UNIX",
        "UsageOperation": "RunInstances"
    }
]
```

**To find the AMI billing information for an instance**  
Use the [describe-instances](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html) command.

```
aws ec2 describe-instances \
    --instance-ids i-1234567890abcdef0 \
    --query "Reservations[].Instances[].{PlatformDetails:PlatformDetails,UsageOperation:UsageOperation}"
```

The following is example output for a Windows instance.

```
[
    {
        "PlatformDetails": "Windows",
        "UsageOperation": "RunInstances:0002"
    }
]
```

------
#### [ PowerShell ]

**To find the AMI billing information for an AMI**  
Use the [Get-EC2Image](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Image.html) cmdlet.

```
Get-EC2Image `
    -ImageId ami-0abcdef1234567890 | `
    Format-List PlatformDetails, UsageOperation
```

The following is example output for a Linux AMI.

```
PlatformDetails : Linux/UNIX
UsageOperation  : RunInstances
```

**To find the AMI billing information for an instance**  
Use the [Get-EC2Instance](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Instance.html) cmdlet.

```
(Get-EC2Instance `
    -InstanceId i-1234567890abcdef0).Instances | `
    Format-List PlatformDetails, UsageOperation
```

The following is example output for a Windows instance.

```
PlatformDetails : Windows
UsageOperation  : RunInstances:0002
```

------

# Verify AMI charges on your bill


To ensure that you're not incurring unplanned costs, you can verify that the billing information for an instance in your AWS Cost and Usage Report (CUR) matches the billing information that's associated with the AMI that you used to launch the instance.

To verify the billing information, find the instance ID in your CUR and check the corresponding value in the `[lineitem/Operation](https://docs.aws.amazon.com/cur/latest/userguide/Lineitem-columns.html#Lineitem-details-O-Operation)` column. That value should match the value for **Usage operation** that's associated with the AMI.

For example, the AMI `ami-0123456789EXAMPLE` has the following billing information:
+ **Platform details** = `Red Hat Enterprise Linux`
+ **Usage operation** = `RunInstances:0010`

If you launched an instance using this AMI, you can find the instance ID in your CUR, and check the corresponding value in the `[lineitem/Operation](https://docs.aws.amazon.com/cur/latest/userguide/Lineitem-columns.html#Lineitem-details-O-Operation)` column. In this example, the value should be `RunInstances:0010`.

# AMI quotas in Amazon EC2
AMI quotas

The following quotas apply to creating and sharing AMIs. The quotas apply per AWS Region.


****  

| Quota name | Description | Default quota per Region | 
| --- | --- | --- | 
| AMIs | The maximum number of public and private AMIs allowed per Region. These include available, pending, and disabled AMIs, and AMIs in the Recycle Bin. | 50,000 | 
| Public AMIs | The maximum number of public AMIs, including public AMIs in the Recycle Bin, allowed per Region. | 5 | 
| AMI sharing | The maximum number of entities (organizations, organizational units (OUs), and accounts) that an AMI can be shared with in a Region. Note that if you share an AMI with an organization or OU, the number of accounts in the organization or OU does not count towards the quota. | 1,000 | 

If you exceed your quotas and you want to create or share more AMIs, you can do the following:
+ If you exceed your total AMIs or public AMIs quota, consider deregistering unused images.
+ If you exceed your public AMIs quota, consider making one or more public AMIs private.
+ If you exceed your AMI sharing quota, consider sharing your AMIs with an organization or OU instead of separate accounts.
+ Request a quota increase for AMIs.

## Request a quota increase for AMIs


If you need more than the default quota for AMIs, you can request a quota increase.

**To request a quota increase for AMIs**

1. Open the Service Quotas console at [https://console.aws.amazon.com/servicequotas/](https://console.aws.amazon.com/servicequotas/).

1. In the navigation pane, choose **AWS services**.

1. Choose **Amazon Elastic Compute Cloud (Amazon EC2)** from the list, or type the name of the service in the search box.

1. Choose the AMI quota to request an increase. The AMI quotas you can select are:
   + AMIs
   + Public AMIs
   + AMI sharing

1. Choose **Request quota increase**.

1. For **Change quota value**, enter the new quota value, and then choose **Request**.

To view any pending or recently resolved requests, choose **Dashboard** from the navigation pane. For pending requests, choose the status of the request to open the request receipt. The initial status of a request is **Pending**. After the status changes to **Quota requested**, you'll see the case number under **Support Center case number**. Choose the case number to open the ticket for your request.

After the request is resolved, the **Applied quota value** for the quota is set to the new value.

For more information, see the [Service Quotas User Guide](https://docs.aws.amazon.com/servicequotas/latest/userguide/request-quota-increase.html).